package com.ytf.dogbox.activity;



import static com.ytf.dogbox.util.TestConfig.ip;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.icu.text.DecimalFormat;
import android.location.Location;
import android.location.LocationManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.util.ArrayMap;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.VideoView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.amap.api.location.AMapLocation;
import com.amap.api.maps.model.LatLng;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.interfaces.OnCancelListener;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;
import com.ytf.dogbox.CountDownTime.CountDownThread;
import com.ytf.dogbox.CountDownTime.OnCountDownListener;
import com.ytf.dogbox.R;
import com.ytf.dogbox.base.BaseOneActivity;
import com.ytf.dogbox.bean.AdvertBean;
import com.ytf.dogbox.bean.AlarmBean;
import com.ytf.dogbox.bean.AlarmPlayBean;
import com.ytf.dogbox.bean.CheckMsgBean;
import com.ytf.dogbox.bean.DogConfigBean;
import com.ytf.dogbox.bean.DogEventBean;
import com.ytf.dogbox.bean.DogExceBean;
import com.ytf.dogbox.bean.DogHttpKeyBean;
import com.ytf.dogbox.bean.DogOtherBean;
import com.ytf.dogbox.bean.DogPriceBean;
import com.ytf.dogbox.bean.DogSnBean;
import com.ytf.dogbox.bean.DogSyncConfigBean;
import com.ytf.dogbox.bean.DogTonkenBean;
import com.ytf.dogbox.bean.DownloadItem;
import com.ytf.dogbox.bean.ErrorBean;
import com.ytf.dogbox.bean.FlowBean;
import com.ytf.dogbox.bean.FlowMsgBean;
import com.ytf.dogbox.bean.HttpPayBean;
import com.ytf.dogbox.bean.KeyMsgBean;
import com.ytf.dogbox.bean.LiveBean;
import com.ytf.dogbox.bean.LiveContentBean;
import com.ytf.dogbox.bean.LiveObjBean;
import com.ytf.dogbox.bean.PayBean;
import com.ytf.dogbox.bean.PayList;
import com.ytf.dogbox.bean.PaySuccessBean;
import com.ytf.dogbox.bean.QiniuMsgBean;
import com.ytf.dogbox.bean.RefundBean;
import com.ytf.dogbox.bean.RefundParamBean;
import com.ytf.dogbox.bean.UpLoadGetBean;
import com.ytf.dogbox.bean.UpLoadGetSubBean;
import com.ytf.dogbox.bean.UpdateRecordBean;
import com.ytf.dogbox.bean.PayValue;
import com.ytf.dogbox.config.SerialConfigUtil;
import com.ytf.dogbox.db.SqliteManager;
import com.ytf.dogbox.db.UploadItem;
import com.ytf.dogbox.dialog.WarnDialog;
import com.ytf.dogbox.dialog.WarnPopup;
import com.ytf.dogbox.dialog.WarnTemPopup;
import com.ytf.dogbox.dogHttp.DogBoxType;
import com.ytf.dogbox.dogHttp.DogContract;
import com.ytf.dogbox.dogHttp.DogPresenter;
import com.ytf.dogbox.dogHttp.DogWashType;
import com.ytf.dogbox.dogHttp.OnUploadListener;
import com.ytf.dogbox.dogHttp.ThreadPoollExcutorUtil;
import com.ytf.dogbox.fragment.AvContentFragment;
import com.ytf.dogbox.fragment.CameraFragment;
import com.ytf.dogbox.fragment.CommandFragment;
import com.ytf.dogbox.fragment.FlowFragment;
import com.ytf.dogbox.fragment.NonNetworkFragment;
import com.ytf.dogbox.fragment.OnePayFragment;
import com.ytf.dogbox.fragment.PayFragment;
import com.ytf.dogbox.inteflyCamera.InteflyCameraFragment;
import com.ytf.dogbox.listener.ICameraListener;
import com.ytf.dogbox.location.gaode.GaodeLocationUtils;
import com.ytf.dogbox.location.google.LocationUtils;
import com.ytf.dogbox.player.PlayItem;
import com.ytf.dogbox.qiniu.QiNiuUtil;
import com.ytf.dogbox.receive.AlarmReciever;
import com.ytf.dogbox.util.*;
import com.ytf.dogbox.dialog.PayDialogUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import cn.hutool.core.date.DateUtil;



public class DogActivity extends BaseOneActivity<DogPresenter> implements
        AlarmReciever.IReceiver,
        DogContract.View,
        MediaPlayer.OnVideoSizeChangedListener,
        MediaPlayer.OnSeekCompleteListener,
        MediaPlayer.OnInfoListener,
        MediaPlayer.OnErrorListener,
        MediaPlayer.OnPreparedListener,
        MediaPlayer.OnCompletionListener,
        OnCountDownListener,
        SocketService.IServiceToActivity,
        TextToSpeech.OnInitListener,
        UpCompletionHandler,
        ICameraListener,
        CommandFragment.CommandListener,
        PayDialogUtil.IPayDialogListener{

    private final String TAG=DogActivity.class.getSimpleName();


    OnePayFragment onePayFragment;
    PayFragment payFragment;

    AvContentFragment upPartContentFragment;
    CameraFragment cameraFragment;
    CommandFragment commandFragment;
    NonNetworkFragment nonNetworkFragment;
    FlowFragment flowFragment;

    private ConcurrentLinkedDeque<String> cacheLinkedDeque = new ConcurrentLinkedDeque<>();//文件上传下载
    private ConcurrentLinkedDeque<String> cacheLinkedDeque1 = new ConcurrentLinkedDeque<>();//杂事处理
    private ConcurrentLinkedDeque<String> cacheLinkedDeque2 = new ConcurrentLinkedDeque<>();//手机信号
    private ConcurrentLinkedDeque<List<AlarmBean>> adcacheLinkedDeque = new ConcurrentLinkedDeque<>();//广告
    private ConcurrentLinkedDeque<DogEventBean> dogLinkedDeque=new ConcurrentLinkedDeque<>();//用来处理狗的事物
    Thread upLoadWorker = null;
    private static Object uploadLock = new Object();
    /**
     * 这个线程专门用来处理播放数据
     */
    Thread ReceiveWorker = null;
    private static Object receiveObject = new Object();

    Thread NetWorker=null;
    private static Object netObject=new Object();

    Thread AdVertWorker=null;
    private static Object advertObject=new Object();

    Thread dogThread=null;      //这个用来检查和处理洗狗机传回来的数据
    private static Object dogObject=new Object();

    // 不在工作状态两分钟后会自动弹出广告框播放广告，点击广告则会跳回洗狗界面
    private boolean isDogBoxWorkingFlag=false;//洗狗机工作状态：空闲状态，工作状态  空闲状态可以弹出窗进行广告播放，工作状态只能展示洗狗的流程状态

    private boolean dogBoxExitFlag=true;//可以作为ondestroy时while循环的更改

    private TextView quickWashTv,detailWashTv,shopTv;
    private TextView warnTv;
    private TextView showPersentTv;
    private TextView snContentTv,deviceStateTv,deviceLinkTv;

    private TextView stopTv,stepTv;
    private TextView versionTv;
    private LinearLayout infoLl;
    private RelativeLayout deskLl;

    private DogWashType dogWashType;
    Thread dryThread;   //洗狗机流程线程
    Thread disinfectionThread;  //洗狗机消毒线程

    /**=======================dogWorker 用来一直获取状态============================*/
    Thread dogWorker;   //用来进行长时间不断往返的工作
    boolean isDestroy=true;

    private int mechineInt=2;
    private boolean locationFlag=true;
    private boolean locationMode=true;      //默认使用GPS定位
    private boolean gpsFlag = true;

    private boolean httpFlag=true;  //进行同步http标志
    private int httpInt=30;

    private boolean dogConfigFlag=true;//洗狗机配置数据
    private int dogConfigInt=300;//5分钟左右进行一次数据上传

    GaodeLocationUtils gaodeLocationUtils;

    int threadTime=1000;
    /**=======================dogWorker 用来一直获取状态--end============================*/

    int gpsInt=20;
    PayDialogUtil payDialogUtil;
    WarnDialog warnDialog;


    SqliteManager sqliteManager;
    ContentValues contentValues = new ContentValues();

    DisplayMetrics displayMetrics;
    float scale = 0;
    int screenHeight = 0;
    int screenWidth = 0;

    boolean tfcardErrorFlag=true;

    private Intent socketServiceIntent;

    private SocketService mSocketService;

    /**================网络状态==================*/
    private boolean isOnNet=true;//网络有网状态
    int netType=100;
    WifiManager manager;
    public TelephonyManager mTelephonyManager;
    public PhoneStatListener mListener;
    private NetWorkBroadCastReciver mNetWorkBroadCastReciver;
    SignalStrength signal;
    private boolean mobileFlag=false;//4G打开状态
    private String currentApName="";
    boolean needOpenWifi=false;

    private int netdo=100;
    private boolean wifiConFlag=true;

    ConnectivityManager connectivityManager;
    private boolean isCheckFlag = true;//开机只跑一次标志
    private int netInt=100;
    private int lastNet=100;//只适用于辨别上一次有用的网络是什么
    private String phoneIp = "";
    private String wlan0Ip="xxxx";//默认4个x
    private boolean networkworkingFlag = true;
    //AP热点初始账号和密码
    private String apName = "lamp";
    private String apPwd = "12345678";
    private int apType = 2;

    /**==================异常信息=====================*/
    private int heatInt=600;//倒计时检测时间  10分钟加热后查看加热后温度对比加热前温度，如果大于2°，则表明传感器是好的，如果没有则表明传感器出现了问题
    private boolean heatFlag=false;//是否继续检测是否还要关水温加热阀门
    private String exceType;
    private String exceMark;
    private boolean refundFlag;//是否需要退款

    /**==================当前洗狗机状态======================*/
    double heatWaterTem=0;//打开加热开关时的水温
    double waterTem=100;//水温多少
    double invirTem;//环境温度多少
    double houseTem;//室温是多少
    double waterTem1=30;
    double houseTem1=30;
    double houseUpper=40;  //用于加热丝的开关判断
    double houseLower=38;  //用于加热丝的开关判断
    boolean doorFlag;//是否开门
    boolean urgenFlag;//紧急按钮控件
    boolean isUrgenFlagDo=true;//用于限制同一状态只显示一次的情况
    boolean waterLevelFlag;//水位是否正常

    private String dogStateStr;

    /**==================当前洗狗机过程======================*/
    String phoneNum="";
    BasePopupView waterlevelView;
    BasePopupView temlevelView;
    private DogBoxType dogBoxType;
    double lowerWater=35;//水温下限
    double upperWater=38;//水温上限
    boolean heatingWaterIsOpenFlag=false;//水箱是否在加热状态
    boolean heatingInvirIsOpenFlag=false;//室内温度是否在加热状态

    int dogboxState=0;//0代表空闲，1代表洗狗中，2代表消毒中
    int leaveTime=0;//剩余多少时间
    int flowLeaveTime=0;//流程里面剩余多少时间
    int flowDogLeaveTime=0;//洗狗流程里面还有多长时间

    //当前处于哪个阶段
    private int stage=101;        //开门，关门，第一次清水冲洗，沐浴露喷洒，第二次清水冲洗，护毛素冲洗，第三次清水冲洗，烘干，开门取狗，关门消毒，清水冲洗（完成）
    boolean touchSwitchFlag=true;//一开始这个开关是接触着的

    int oneWaterInt=35000;//第一次清水冲洗时间
    int bodyWashInt=20000;//喷沐浴露时间(阶段时间)
    int bodyWashInt1=10000;//喷沐浴露时间(真正喷沐浴露时间)
    int twoWaterInt=25000;//第二次喷水冲洗时间
    int conditionerInt=20000;//喷护毛素时间(阶段时间)
    int conditionerInt1=10000;//喷护毛素时间(真正喷护毛素时间)
    int threeWaterInt=60000;//第三次喷水冲洗时间
    int preheatInt=15000;//烘干预热时间  用于第一次流程等待
    int preheatInt1=30*1000;//烘干加热间隔时间
    int preheatInt2=15000;//烘干断电间隔时间
    int dryInt=30000;//烘干默认时间
    int disinfectantInt=5000;//消毒液喷洗时间
    int windChangeInt=10000;//往洗狗机里面吹风，换风机时间
    int fourWaterInt=10000;//第四次喷水冲洗，冲洗消毒液
    int stepInterval=17*1000;//步骤间隔
    double totalMul=1;


    String token;
    /**====================金额配置=======================*/
    double oneKeyWashPrice=0.01;
    double detailWashPrice=10;
    double smallDogPrice=0.8;
    double midDogPrice=1;
    double bigDogPrice=1.5;
    double nonHairPrice=0.8;
    double shortHairPrice=0.9;
    double normalLongHairPrice=1.0;
    double longHairPrice=1.3;
    double thinHairPrice=0.9;
    double normalHairPrice=1.0;
    double thickHairPrice=1.3;
    double dryDogPrice=0.6;
    double washDryPrice=1;
    double waterPrice;

    /**================订单成功后==================*/
    String order_No;
    double order_amount;
    String order_state;
    String trade_no;
    /**===============支付功能==================**/

    String washContent;
    Bitmap urlBmp;
    String payUrl;  //支付url
    String orderNo; // 支付订单
    double amount;  //支付金额
    String washType="QUICKWASH";//清洗类型
    String payContent;
    String doyType;//狗的大小
    String hairType;//狗毛发的长短
    String hairthick;//狗毛发的厚薄
    String washTp;//洗狗的类型
    String tem;//洗狗的水温

    /**============功能码==============*/
    String function = "";
    /**====================版本相关=======================*/
    private String pversion;//上一次的设备版本号
    private String lBoardVersion;//上一次的主板版本号
    private boolean isCallBoardVersion=false;//是否为呼唤主板版本
    Map<String, Object> verParams;

    String mechineModel="";
    String appVersion = "";
    int appVersionCodeInt=0;
    /**====================================VideoView==========================================*/
    boolean isVvOnPlay = false;
    VideoView vv;


    /**======================================文本转语音相关====================================*/
    private TextToSpeech textToSpeech;

    TtsProgress ttsProgress;
    String sLanguage;
    private int avVolumn = 15;
    boolean speakIsStart = true;
    String warnMsg = "";
    int speakTime = 0;
    String speakContent;
    private int avAlarmId = -1;

    /**==========================================广告相关=====================================================*/
    private String showUrl="/product/media/show.mp4";
    private String currentFile=null;//当前正在播放的url
    private boolean isHasLiveFlag = false;//用户是否设置了直播这个，主要是开机重启的时候使用
    private boolean adverFlag=true; //开机广告只搞一次
    private boolean fromLiveFlag = true;//直播结束标志
    private boolean firstInitCountryFlag = true;  //仅仅使用在一次开机判断指令
    private boolean isLiveFlag = false;//是否是直播  1，开机判断；2，指令判断
    private String sdPath;
    MediaPlayer mPlayer;
    int currentVolumn = 0;
    private int alarmId = -1;
    private boolean isPlayOn = false;//广告是否在播放，主要用来判断更改设备音量值使用
    private boolean isVolumeOn = false;//是否是音量一直如此
    int fixedVolume = 0;//固定的音量值是多少
    private int freeVolumn = 0;   //闲时音量值
    ArrayList<PlayItem> playItems = null;//这个是音视频的播放列表
    ArrayList<PlayItem> playItemBackpackages = null;//用来播放出错时的准备
    private boolean isInAdvertisement = false;//是否在播放广告（包括普通广告，公益广告，直播）里面
    private boolean isAdvertisement = false;//是否在广告播放（包括普通广告，公益广告）里面
    boolean isPlay = true;//是否处于播放的流程里面
    boolean isInFreeAdFlag = true;  //是否是处于空闲广告之中
    private CountDownThread countDownThread;    //图片倒计时
    private boolean isNullFlag = false;//列表为空的标志
    private boolean isdownloadFlag = true;   //可以下载标志
    private ThreadPoollExcutorUtil threadPoollExcutorUtil;
    private int musicVolumn = 0;

    int playInt = 0;  //音视频列表排列

    Lock lock=new ReentrantLock();

    Map<String, Object> downParams = new ArrayMap<>();
    /**============================================广告相关===============================================*/
    /**=====================================文件上传下载 start============================================*/
    UploadItem uploadItem;
    String md5;
    boolean isCurDoPolice = false;
    boolean qiniuFlag=false;
    Map<String, String> uploadParams = new HashMap<>();
    private boolean isNotUpload = true; //是否可以上传标志
    UploadManager uploadManager;//七牛云文件上传管理
    private int sdcardErrorCode;//tfcard报错标志
    int sqlInt = 0;

    private int isdownloadInt=60;
    Map<String, String> policeMap = new ArrayMap<>();
    Map<String, String> sycnDataMap = new ArrayMap<>();
    /**=====================================文件上传下载 end============================================*/
    /**=====================================摄像头 start============================================*/

    String publishStr;
    private boolean isQiniuFlag = false;  //是否创建了七牛云
    private boolean canRecordFlag=true;

    /**=====================================摄像头 end============================================*/

    Map<String, String> params;
    Map<String,String> errorMap;

    AudioManager audioManager;
    public final int FREEADV=1;//闲时广告
    public final int SINGLESONG = 2;   //单曲循环
    public final int LISTSONG = 3;   //列表播放
    public final int SHOWPICTURE = 4;   //显示图片
    public final int LIVEAD=5;          //播放直播
    public final int DOWNLOADQINIU=6;   //在七牛云下载
    public final int WARNSHOW=7;    //warnTv的设置
    public final int SCREENVOLUME=8;//原先的开关屏，现在不要开关屏
    public final int POLICEPITUREUPDATE = 9;   //上传警报(开门放狗)图片
    public final int RECORDUPLOAD = 10;   //上传历史等信息
    public final int RECORDDEL = 11;   //终端删除历史视频之后给服务器上报
    public final int MERGE=12;  //合并
    public final int UPERROR=13;//上传错误代码
    public final int VERSIONKEY=14;//获取key
    public final int VERSION=15;//获取版本
    public final int DOGPAYURL=16;//一键洗狗和高精洗狗 请求服务器去获取二维码
    public final int DOGPAYONESHOW=17;//一键洗狗订单显示
    public final int DOGPAYSHOW=18;//高精洗狗订单显示
    public final int DOGPAYSUCCESS=19;//支付成功页面
    public final int DOGREFUNDPAY=20;
    public final int DOGEXCEPTIONUPLOAD=21;//洗狗机异常上报
    public final int SHOWFLOW=22;//显示流程
    public final int DOGCLOSEDOORSHOW=23;//洗狗机关门页面
    public final int DOGCLOSEDOORDISMISSSHOW=24;//洗狗机关门页面消失
    public final int DOGURGENSHOW=25;//洗狗机紧急页面打开
    public final int DOGURGENDISMISS=26;//洗狗机紧急页面消失
    public final int NONETWORK=27;//显示无网络界面
    public final int DISINFECTANTSSHOW=28;//消毒页面打开
    public final int DISINFECTANTSDISMISS=29;//消毒页面关闭
    public final int DOGOPENDOORSHOW=30;//洗狗机开门页面
    public final int DOGOPENDOORDISMISSSHOW=31;//洗狗机关门页面
    public final int DOGDEVICESTATE=32;//洗狗机当前状态
    public final int DOGTOKEN=33;//洗狗机token
    public final int DOGFLOWTIME=34;//洗狗机洗漱流程时间
    public final int DOGSYNCCONFIG=35;//洗狗机同步

    private Handler handler=new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case FREEADV: {

                    lock.lock();
                    Log.i(TAG, "startplay handleMessage: 播放出错到19");
                    try {

                        isInAdvertisement = false;
                        isAdvertisement = false;
                        isInFreeAdFlag=true;
                        upPartContentFragment.showVideo(mPlayer,showUrl);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }finally {
                        lock.unlock();
                    }
                    break;
                }
                case SINGLESONG:{
                    lock.lock();
                    try {
                        int code=0;
                        String file= (String) msg.obj;
                        currentFile=file;
                        if (playItems != null && playItems.size()>0 && playItems.get(0).getPlayType() == 1) {
                            //从这里上传播放的文件
//                            playItems.get(0).getPlayName()

                            if (mPlayer.isPlaying()){
                                mPlayer.stop();
                                mPlayer.reset();
                                mPlayer.setDisplay(null);
                            }else{
                                mPlayer.reset();
                            }

                            upPartContentFragment.showMusic();
                            try {
                                mPlayer.setDataSource(file);
                                mPlayer.prepareAsync();
                                mPlayer.setLooping(true);
                            } catch (IOException e) {
                                e.printStackTrace();
                                code=-1;
                            }
                        } else {
                            upPartContentFragment.showVideo(mPlayer,file);
                        }

                        if (code==-1){
                            playItems = null;
                            isPlay = true;
                            playMediaFile();
                        }
                    }finally {
                        lock.unlock();
                    }
                    break;
                }
                case LISTSONG:{
                    //播放歌曲之前将其清除掉
                    lock.lock();
                    try {
                        int code=0;
                        String file= (String) msg.obj;
                        currentFile=file;
                        Log.i(TAG, "handleMessage: 音视频需要播放的文件地址为="+file+";正在播放？="+mPlayer.isPlaying() );
                        int xing=msg.arg1;
                        if (playItems != null && xing < playItems.size() && xing>=0 && playItems.get(xing).getPlayType() == 1) {

                            if (mPlayer.isPlaying()){
                                mPlayer.stop();
                                mPlayer.reset();
                                mPlayer.setDisplay(null);
                            }else{
                                mPlayer.reset();
                            }

                            upPartContentFragment.showMusic();
                            try {
                                mPlayer.setDataSource(file);
                                mPlayer.prepareAsync();
                            } catch (IOException e) {
                                e.printStackTrace();
                                code=-1;
                            }
                        } else {
                            upPartContentFragment.showMulVideo(mPlayer,file);
                        }

                        if (code==-1){
                            playFailInt++;
                            mPlayer.stop();
                            if (playFailInt > 5) {
                                playItems = null;
                                isPlay = true;
                                playMediaFile();
                            } else {
                                startPlay();
                            }
                        }
                    }finally {
                        lock.unlock();
                    }



                    break;
                }
                case SHOWPICTURE:{
                    //播放列表里面显示图片
                    //图片  获取图片显示时长
                    Bitmap bitmap= (Bitmap) msg.obj;
                    int playTime = msg.arg1;
                    int playTimeOrNot = msg.arg2;

                    if (bitmap != null) {

                        Log.i(TAG, "handleMessage: 广告图片显示,直播显示标志="+isLiveFlag );
                        if (!isLiveFlag){
                            if (mPlayer.isPlaying()){
                                mPlayer.stop();
                                mPlayer.reset();
                                mPlayer.setDisplay(null);
                            }

                            upPartContentFragment.showImage(bitmap);
                            Log.i(TAG, "handleMessage: 是否为单张图片="+playTimeOrNot+";播放时间="+playTime);
                            if (playTimeOrNot == 1) {
                                if (playTime <= 0) {
                                    startCountDown(10);
                                } else {
                                    startCountDown(playTime);
                                }
                            }
                        }else {
                            bitmap=null;
                        }

                    }


                    break;
                }
                case LIVEAD:{
                    lock.lock();
                    try {
                        String file= (String) msg.obj;
                        upPartContentFragment.showMulVideo(mPlayer,file);
                    }catch (Exception e){
                        e.printStackTrace();
                    }finally {
                        lock.unlock();
                    }
                    break;
                }
                case DOWNLOADQINIU: {
                    String downloadMd5 = (String) msg.obj;
                    Log.i(TAG, "handleMessage: 在主线程去获取七牛云的下载地址" + downloadMd5+";是否在下载="+isdownloadFlag);
                    if (downParams!=null){
                        downParams.clear();
                        downParams.put(UploadConfig.ATTACH, true);
                        downParams.put(UploadConfig.endUser, "DEVICELIG");
                        downParams.put(UploadConfig.md5, downloadMd5);
                        downParams.put(UploadConfig.owner, FlyUtil.getSn(DogActivity.this));
                        downParams.put(UploadConfig.experies, 6000);
                        mPresenter.getQiniuDownloadUrl(downParams);
                    }else{
                        downParams = new ArrayMap<>();
                    }

                    break;
                }
                case WARNSHOW:{
                    int warnInt=msg.arg1;
                    if (warnInt==1){
                        //这个是开启
                        String value= (String) msg.obj;
                        warnTv.setVisibility(View.VISIBLE);
                        warnTv.setText(value);
                    }else{
                        //这个是隐去
                        warnTv.setVisibility(View.INVISIBLE);
                    }
                    break;
                }
                case SCREENVOLUME:{
                    if (!vv.isPlaying() && !textToSpeech.isSpeaking()) {
                        if (isVolumeOn) {
                            audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, fixedVolume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
                        } else {
                            audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, musicVolumn, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
                        }
                        Log.i(TAG, "receiveWork: 开屏列表得到时的声音值="+musicVolumn +";是否恒定音量="+isVolumeOn);
                    } else {
                        if (isVolumeOn){
                            currentVolumn = fixedVolume;
                        }else{
                            currentVolumn=musicVolumn;
                        }


                    }
                    Log.i(TAG, "receiveWork: 开屏列表得到时的声音值=" + currentVolumn);

                    break;
                }
                case POLICEPITUREUPDATE: {
                    if (mPresenter != null && policeMap != null) {
                        Log.i(TAG, "handleMessage: 人脸识别 报警图片上报");
                        mPresenter.getUpdatePolice(policeMap);
                    }
                    break;
                }
                case RECORDUPLOAD: {
                    //如果mp4是好的，则上传一条数据告知服务器，以作客户端观看历史数据使用
                    String rccontent = (String) msg.obj;
                    String[] result = rccontent.split(",");
                    if (result.length == 1) {
                        Log.i(TAG, "handleMessage: 历史 只有一条数据" + result[0]);
                        HashMap<String, Object> map = new HashMap<>();
                        map.put("formattime", result[0]);
                        map.put("sn", FlyUtil.getSn(DogActivity.this));
                        String inw01 = null;
                        try {
                            inw01 = SignUtil.sign(map, FlyUtil.getSn(DogActivity.this));

                            map.put(UploadConfig.SIGN, inw01);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        map.put("sign", inw01);


                        mPresenter.updateRecordMsg(map, result[0], null);
                    } else if (result.length == 2) {
                        Log.i(TAG, "handleMessage: 历史只有两条数据" + result[0] + ";" + result[1]);
                        HashMap<String, Object> map = new HashMap<>();
                        map.put("formattime", result[0]);
                        map.put("cover", result[1]);
                        map.put("sn", FlyUtil.getSn(DogActivity.this));
                        String inw01 = null;
                        try {
                            inw01 = SignUtil.sign(map, FlyUtil.getSn(DogActivity.this));

                            map.put(UploadConfig.SIGN, inw01);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        map.put("sign", inw01);


                        mPresenter.updateRecordMsg(map, result[0], result[1]);
                    }


                    break;
                }
                case RECORDDEL: {
                    //终端删除文件后，会上报一条数据给服务器。告诉服务器已删除数据
                    String rccontent = (String) msg.obj;
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("formattime", rccontent);
                    map.put("sn", FlyUtil.getSn(DogActivity.this));
                    String inw01 = null;
                    try {
                        inw01 = SignUtil.sign(map, FlyUtil.getSn(DogActivity.this));

                        map.put(UploadConfig.SIGN, inw01);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    map.put("sign", inw01);

                    mPresenter.delRecordMsg(map, rccontent);
                    break;
                }
                case MERGE:{
                    String md5= (String) msg.obj;
                    merge(md5);
                    break;
                }
                case UPERROR:{
                    if (!isOnNet)break;
                    try {
                        mPresenter.upSendError(errorMap);
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                    break;
                }
                case VERSIONKEY:{
                    mPresenter.getUpdateKey(verParams);
                    break;
                }
                case VERSION:{
                    mPresenter.updateMsg(verParams);
                    break;
                }
                case DOGPAYONESHOW:{
                    changePayOneMsg(urlBmp,orderNo,amount);


                    break;
                }
                case DOGPAYURL:{
                    getPayUrl(dogWashType);
                    break;
                }
                case DOGPAYSHOW:{
                    changePayMsg(urlBmp,orderNo,amount);
                    break;
                }
                case DOGPAYSUCCESS:{
                    if ("一键洗狗".equals(washContent)){
//                        if (payOneDialog!=null){
//                            payOneDialog.dismiss();
//                        }
                        dismissPayOneDialog();
                    }else{
                        dismissPayDialog();
//                        if (payDialog!=null){
//                            payDialog.dismiss();
//                        }
                    }
                    if (flowFragment==null){
                        flowFragment=new FlowFragment();
                    }
                    replaceFragment(R.id.command_fl,flowFragment);
                    flowFragment.setFlowShow(3);
//                    if (flowFragment!=null){
//
//                    }
                    showPaySuccessDialog();
                    break;
                }
                case DOGREFUNDPAY:{
                    if (token!=null){
                        RefundParamBean refundParamBean=new RefundParamBean();
                        refundParamBean.setAmout(order_amount);
                        refundParamBean.setOrderNo(order_No);
                        refundParamBean.setTradeNo(trade_no);
                        mPresenter.refundPay(refundParamBean,token);
                    }

                    break;
                }
                case DOGEXCEPTIONUPLOAD:{
                    if (token!=null){
                        DogExceBean dogExceBean=new DogExceBean();
                        dogExceBean.setSn(FlyUtil.getSn(DogActivity.this));
                        dogExceBean.setExceName("流程"+stage);
                        dogExceBean.setExceType(exceType);
                        dogExceBean.setRemark(exceMark);
                        String now= DateUtil.now();
                        dogExceBean.setUpTime(now);
                        mPresenter.upLoadDogException(dogExceBean,token);
                    }

                    break;
                }
                case SHOWFLOW:{
                    int num=msg.arg1;
                    if (num==9){
                        if (stopTv!=null){
                            stepTv.setVisibility(View.INVISIBLE);
                            stopTv.setVisibility(View.INVISIBLE);
                            infoLl.setVisibility(View.VISIBLE);
                            deskLl.setBackground(getDrawable(R.mipmap.main_activity_bg));
                        }
                        enterFullscreenAds();
                    }else {
                        if (stopTv!=null){
                            stepTv.setVisibility(View.VISIBLE);
                            stopTv.setVisibility(View.VISIBLE);
                            infoLl.setVisibility(View.INVISIBLE);

                            deskLl.setBackground(getDrawable(R.mipmap.dialogbg));
                            if (findViewById(R.id.qrcode_iv).getVisibility() == View.VISIBLE) {
                                existFullscreenAds();
                            }
                        }
                        if (flowFragment==null){
                            flowFragment=new FlowFragment();
                        }
                        if (flowFragment!=null){
                            Log.e(TAG, "handleMessage: 进入设置流程值="+num );
                            flowFragment.setFlowShow(num);
                        }
                    }
                    break;
                }
                case DOGCLOSEDOORSHOW:{
                    if (stage==1){
                        dismissPaySuccessDialog();
                    }
                    String dogMsg= (String) msg.obj;
                    getWarnDiglog();
                    warnDialog.showCloseDoorDialog(DogActivity.this,DogActivity.this,null,dogMsg);
//                    doorPopupView=new XPopup.Builder(DogActivity.this).asCustom(new DoorPopup(DogActivity.this,dogMsg));
//                    doorPopupView.show();
                    break;
                }
                case DOGCLOSEDOORDISMISSSHOW:{
                    getWarnDiglog();
                    warnDialog.dismissCloseDoorDialog();
//                    if (doorPopupView!=null){
//                        doorPopupView.dismiss();
//                    }
                    break;
                }
                case DOGURGENSHOW:{
                    showUrgenDialog();
                    break;
                }
                case DOGURGENDISMISS:{
                    dismissUrgenDialog();
                    break;
                }
                case NONETWORK:{
                    replaceFragment(R.id.command_fl,nonNetworkFragment);
                    break;
                }
                case DISINFECTANTSSHOW:{
                    getWarnDiglog();
                    warnDialog.showDisinfectants(DogActivity.this,DogActivity.this);
                    break;
                }
                case DISINFECTANTSDISMISS:{
                    getWarnDiglog();
                    warnDialog.dismissDisinfectantsDialog();
                    break;
                }
                case DOGOPENDOORSHOW:{
                    if (stage==1){
                        dismissPaySuccessDialog();
                    }
                    String dogMsg= (String) msg.obj;
                    getWarnDiglog();
                    warnDialog.showOpenDoorDialog(DogActivity.this,DogActivity.this,null,dogMsg);
//                    doorPopupView=new XPopup.Builder(DogActivity.this).asCustom(new DoorPopup(DogActivity.this,dogMsg));
//                    doorPopupView.show();
                    break;
                }
                case DOGOPENDOORDISMISSSHOW:{
                    getWarnDiglog();
                    warnDialog.dismissOpenDoorDialog();
//                    if (doorPopupView!=null){
//                        doorPopupView.dismiss();
//                    }
                    break;
                }
                case DOGDEVICESTATE:{
                    String content= (String) msg.obj;
                    Log.e(TAG, "handleMessage: 状态信息为="+content);
                    if (deviceStateTv!=null && content!=null){
                        if (!"正常".equals(content)){
                            deviceStateTv.setTextColor(getColor(R.color.color_red));
                        }else{
                            deviceStateTv.setTextColor(getColor(R.color.white_color_text));
                        }
                        deviceStateTv.setText(content);
                    }

                    break;
                }
                case DOGTOKEN:{
                    try {
                        DogHttpKeyBean dogHttpKeyBean=new DogHttpKeyBean();
                        String dogsn=FlyUtil.getSn(DogActivity.this);
                        dogHttpKeyBean.setSn(dogsn);
                        dogHttpKeyBean.setName("intefly");
                        String time=DateUtil.now();
                        dogHttpKeyBean.setAccessTime(time);
                        String md5=MD5Util.md5(dogsn+time);
                        md5=md5.toUpperCase();
                        dogHttpKeyBean.setAccessKey(md5);
                        mPresenter.getHttpKey(dogHttpKeyBean);
                    } catch (MD5UtilException e) {
                        throw new RuntimeException(e);
                    }
                    break;
                }
                case DOGFLOWTIME:{
                    long time = (long) msg.obj;
                    int step=msg.arg1;
                    Log.e(TAG, "handleMessage: 往后减的值为="+time+"秒" );
                    setWashDetail(time/1000,step);
                    break;
                }
                case DOGSYNCCONFIG:{
                    DogSnBean dogSnBean=new DogSnBean();
                    dogSnBean.setSn(FlyUtil.getSn(DogActivity.this));
                    long time=PreferenceUtil.getLong(PreferenceUtil.DOGCONFIGTIME,948184723000l);//948184723000
                    Log.e(TAG, "handleMessage: 同步配置上传的时间戳为="+time );
                    dogSnBean.setSyncTime(time);
                    mPresenter.syncConfigData(dogSnBean,token);
                    break;
                }
            }

        }
    };



    private Map<String,String> getParams(){
        if (params==null){
            params=new ArrayMap<>();
        }
        return params;
    }

    private Map<String, Object> getVerParams(){
        if (verParams==null){
            verParams=new ArrayMap<>();
        }
        return verParams;
    }

    private Map<String,String> getErrorMap(){
        if (errorMap==null){
            errorMap=new ArrayMap<>();
        }
        return errorMap;
    }

    private void merge(String md5) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //合并
                getParams().clear();
                params.put(UploadConfig.md5, md5);
                params.put(UploadConfig.devicelig, "DEVICELIG");
                params.put(UploadConfig.owner, FlyUtil.getSn(DogActivity.this));
//                Log.i(TAG, "merge: "+md5 );
                mPresenter.getMerge(params,null);
            }
        });


    }

    private void merge(String md5,String originName) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //合并
                getParams().clear();
                params.put(UploadConfig.md5, md5);
                params.put(UploadConfig.devicelig, "DEVICELIG");
                params.put(UploadConfig.owner, FlyUtil.getSn(DogActivity.this));
//                Log.i(TAG, "merge: "+md5 );
                mPresenter.getMerge(params,originName);
            }
        });


    }


    int nonOperationNum=3*60; //初始3分钟时间，如果没操作，则跳到全屏广告
    Thread thingsWorker=new Thread(new Runnable() {
        @Override
        public void run() {


            if (nonOperationNum<=0 && nonOperationNum!=-10){
                //跳转到全屏广告去
                nonOperationNum=-10;//避免多次跳进来
                Log.e(TAG, "run: 跳转到全屏广告咯" );


            }else{
                if (nonOperationNum!=-10){
                    nonOperationNum--;
                }
            }


        }
    });



    /**
     * 服务相关
     */
    private final ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            mSocketService = ((SocketService.LocalBinder) service).getService();
//            controlSocketServicek=((ControlSocketService.LocalBinder)service).getService();
            if (mSocketService != null) {
                mSocketService.setIService(DogActivity.this);
                mSocketService.closeAllSwitch();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mSocketService = null;
        }
    };

    //根据功能和需求组装碎片
    FragmentManager fragmentManager;

    private void replaceFragment(int containerViewId, Fragment fragment) {
        fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();//开启一个事物
        transaction.replace(containerViewId, fragment);
        transaction.commit();
    }

    private void replaceDiglogFragment(FrameLayout frameLayout, Fragment fragment) {
        FragmentManager  fragmentManager  =  getSupportFragmentManager();
        FragmentTransaction  transaction  =  fragmentManager.beginTransaction();

        //  设置  transition  动画
        transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        //  将新的  fragment  添加到  FrameLayout  中
        frameLayout.addView(fragment.getView());

//  提交事务
        transaction.commitAllowingStateLoss();
    }

    @Override
    public int getLayout() {
        displayMetrics = getResources().getDisplayMetrics();
        scale = displayMetrics.density;
        return R.layout.activity_dog;
    }

    @Override
    public void initView(Object obj) {
        AlarmReciever.setiReceiver(this);

//        quickWashTv=findViewById(R.id.quick_wash);
//        detailWashTv=findViewById(R.id.detail_wash);
//        shopTv=findViewById(R.id.shop);
        warnTv=findViewById(R.id.warnTv);
        stopTv=findViewById(R.id.stop_tv);
        stepTv=findViewById(R.id.step_tv);
        infoLl=findViewById(R.id.device_info_layout);
        deskLl=findViewById(R.id.desk_ll);
        snContentTv=findViewById(R.id.device_sn_content);
        deviceStateTv=findViewById(R.id.device_state_tv);
        deviceLinkTv=findViewById(R.id.device_link_tv);
        vv=findViewById(R.id.vv);
        showPersentTv = findViewById(R.id.showpersent);
        versionTv=findViewById(R.id.version);

        snContentTv.setText(FlyUtil.getSn(DogActivity.this));

        //预先先弹出一次弹窗，以免第一次弹窗时间要太久
//        showDetailDialog();


        screenHeight = displayMetrics.heightPixels;
        screenWidth = displayMetrics.widthPixels;

//        dogtypes=getResources().getStringArray(R.array.dog_type);
//        dogHairLongs=getResources().getStringArray(R.array.dog_hair_type);
//        dogHairThins=getResources().getStringArray(R.array.dog_thin_type);
//        dogWashTypes=getResources().getStringArray(R.array.dog_wash_type);

        Log.e(TAG, "initView: 进行控件的初始化 screenHeight高="+screenHeight+";宽="+screenWidth+";scale="+scale );

        uploadManager = new UploadManager();
        sdcardErrorCode= PreferenceUtil.getInt(PreferenceUtil.SDCARDERRORFLAG,0);
        if (sdcardErrorCode==1){
            tfcardErrorFlag=false;
        }


        audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        sqliteManager = SqliteManager.getInstance(DogActivity.this, "dogbox", 2);
        //将无故断掉导致状态为3的文件下载重新变成1
        if (sqliteManager != null) {
            sqliteManager.updateAllDownloadFlag(1);
        }

        manager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);

        //获取telephonyManager
        mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        //开始监听
        mListener = new PhoneStatListener();
        connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        mNetWorkBroadCastReciver = new NetWorkBroadCastReciver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ConnectivityManager.EXTRA_EXTRA_INFO);
        intentFilter.addAction(ConnectivityManager.EXTRA_NETWORK);
        intentFilter.addAction(ConnectivityManager.EXTRA_NETWORK_TYPE);
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        intentFilter.addAction(WifiManager.RSSI_CHANGED_ACTION);
        intentFilter.addAction("android.net.wifi.WIFI_AP_STATE_CHANGED");
        registerReceiver(mNetWorkBroadCastReciver, intentFilter);

        ttsProgress=new TtsProgress();
        textToSpeech = new TextToSpeech(DogActivity.this, DogActivity.this);
        textToSpeech.setOnUtteranceProgressListener(ttsProgress);

        sLanguage = LanguageUtil.currentLanguage(DogActivity.this);
        Log.e(TAG, "initView: 当前设备语言为="+sLanguage);

        sdPath = FileSortUtil.getStoragePath(this, true);

        FileSortUtil.createAppPath(sdPath);
        Log.i(TAG, "initView: 外部sd卡的路径为：" + sdPath);

        socketServiceIntent = new Intent(DogActivity.this, SocketService.class);
        bindService(socketServiceIntent, mServiceConnection, BIND_AUTO_CREATE);

        upPartContentFragment = new AvContentFragment();
        replaceFragment(R.id.adFragment, upPartContentFragment);

        commandFragment=new CommandFragment();
        commandFragment.setCommandListener(this);
        replaceFragment(R.id.command_fl,commandFragment);

        flowFragment=new FlowFragment();
        nonNetworkFragment=new NonNetworkFragment();

        cameraFragment=new InteflyCameraFragment();
        replaceFragment(R.id.camera,cameraFragment);

        cameraFragment.setCameraListener(this);
        cameraFragment.setFragmentParams(sqliteManager);

        mPresenter = new DogPresenter();
        mPresenter.attachView(this);

        mPlayer = new MediaPlayer();
        mPlayer.setOnCompletionListener(this);
        mPlayer.setOnVideoSizeChangedListener(this);
        mPlayer.setOnInfoListener(this);
        mPlayer.setOnErrorListener(this);
        mPlayer.setOnPreparedListener(this);
        mPlayer.setOnSeekCompleteListener(this);
        try {
            handler.sendEmptyMessage(FREEADV);
//            isStart = true;
            isPlay = false;
        } catch (Exception e) {
            e.printStackTrace();
            Log.i(TAG, "startPlayer: 播放出错44" + mPlayer);
            Log.i(TAG, "startPlayer: 播放出错44" + e.getMessage());
        }

        PackageManager pm = getPackageManager();

        try {
            PackageInfo pi = pm.getPackageInfo(getPackageName(), 0);
            appVersion = pi.versionName;
            appVersionCodeInt=pi.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        mechineModel=FlyUtil.getMeChineModel(this);
        Log.i(TAG, "initView: 设备的硬件名称为="+mechineModel );

        //开启软路由
        try {
            FlyUtil.lanSoftAp(DogActivity.this,1);
        }catch (Exception e){
            e.printStackTrace();
        }


        String string = PreferenceUtil.getString(PreferenceUtil.VERSION, "1");
        if (!"1".equals(string)) {
            if (string.equals(appVersion)) {
                Log.i(TAG, "initView: 同一个版本，不重启");
            } else {
                Log.i(TAG, "initView: 不是同一版本，重启");
                //保存这个版本
                PreferenceUtil.commitString(PreferenceUtil.VERSION, appVersion);
                //重启一次设备
//                FlyUtil.initInot(this).execSuCmd("reboot");
                FlyUtil.rebootMechine(DogActivity.this);
            }
        } else {
            //如果第一次为1，则需要将其写入版本
            Log.i(TAG, "initView: 第一次写入版本");
            PreferenceUtil.commitString(PreferenceUtil.VERSION, appVersion);
        }

        String upversion = PreferenceUtil.getString(PreferenceUtil.UPVERSION, "-1");
        if ("-1".equals(upversion)) {
            pversion = null;
        } else {
            pversion = upversion;
        }

        String upBoardversion = PreferenceUtil.getString(PreferenceUtil.BOARDVERSION, "-1");
        if ("-1".equals(upBoardversion)) {
            lBoardVersion = null;
        } else {
            lBoardVersion = upBoardversion;
        }

        token=PreferenceUtil.getString(PreferenceUtil.DOGTOKEN,null);
        oneKeyWashPrice=Double.parseDouble(PreferenceUtil.getString(PreferenceUtil.ONEWASHPRICE, "0.01"));
        if (oneKeyWashPrice<=0.01){
            oneKeyWashPrice=0.01;
        }
        detailWashPrice=Double.parseDouble(PreferenceUtil.getString(PreferenceUtil.DETAILWASHPRICE, "0.01"));
        if (detailWashPrice<=0.01){
            detailWashPrice=0.01;
        }
        smallDogPrice=Double.parseDouble(PreferenceUtil.getString(PreferenceUtil.SMALLDOG, "1"));
        midDogPrice=Double.parseDouble(PreferenceUtil.getString(PreferenceUtil.MIDDOG, "1"));
        bigDogPrice=Double.parseDouble(PreferenceUtil.getString(PreferenceUtil.BIGDOG, "1"));
        shortHairPrice=Double.parseDouble(PreferenceUtil.getString(PreferenceUtil.SHORTHAIR, "1"));
        normalLongHairPrice=Double.parseDouble(PreferenceUtil.getString(PreferenceUtil.NORMALLONGHAIR, "1"));
        longHairPrice=Double.parseDouble(PreferenceUtil.getString(PreferenceUtil.LONGHAIR, "1"));
        thinHairPrice=Double.parseDouble(PreferenceUtil.getString(PreferenceUtil.THINHAIR, "1"));
        normalHairPrice=Double.parseDouble(PreferenceUtil.getString(PreferenceUtil.NORMALHAIR, "1"));
        thickHairPrice=Double.parseDouble(PreferenceUtil.getString(PreferenceUtil.THICKHAIR, "1"));
        dryDogPrice=Double.parseDouble(PreferenceUtil.getString(PreferenceUtil.DRYDOG, "1"));
        washDryPrice=Double.parseDouble(PreferenceUtil.getString(PreferenceUtil.WASHDRYDOG, "1"));
        oneWaterInt=PreferenceUtil.getInt(PreferenceUtil.FIRSTWATERTIME,35*1000);
        bodyWashInt=PreferenceUtil.getInt(PreferenceUtil.BODYWASHTIME,20*1000);
        bodyWashInt1=PreferenceUtil.getInt(PreferenceUtil.BODYWASHUSE,10*1000);
        twoWaterInt=PreferenceUtil.getInt(PreferenceUtil.SECONDWATERTIME,25*1000);
        conditionerInt=PreferenceUtil.getInt(PreferenceUtil.CONDITIONERTIME,20*1000);
        conditionerInt1=PreferenceUtil.getInt(PreferenceUtil.CONDITIONERUSE,10*1000);
        threeWaterInt=PreferenceUtil.getInt(PreferenceUtil.THIRDWATERTIME,60*1000);
        dryInt=PreferenceUtil.getInt(PreferenceUtil.DRYTIME,2100*1000);
        disinfectantInt=PreferenceUtil.getInt(PreferenceUtil.DISINFECTANTTIME,5*1000);
        windChangeInt=PreferenceUtil.getInt(PreferenceUtil.WINDINPUTTIME,10*1000);
        fourWaterInt=PreferenceUtil.getInt(PreferenceUtil.FOURTHWATERTIME,10*1000);
        stepInterval=PreferenceUtil.getInt(PreferenceUtil.STEPINTERVAL,17*1000);
        phoneNum=PreferenceUtil.getString(PreferenceUtil.BSIZEPHONE,"");
        lowerWater=Double.parseDouble(PreferenceUtil.getString(PreferenceUtil.LOWTEM, "20"));
        upperWater=Double.parseDouble(PreferenceUtil.getString(PreferenceUtil.HIGHTEM, "38"));
        houseLower=Double.parseDouble(PreferenceUtil.getString(PreferenceUtil.LOWINVIRTEM, "35"));
        houseUpper=Double.parseDouble(PreferenceUtil.getString(PreferenceUtil.HIGHINVIRTEM, "38"));

        deviceLinkTv.setText(phoneNum);
        versionTv.setText(appVersion);

        stopTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e(TAG, "onClick: 你点击了停止洗狗操作" );

                new XPopup.Builder(DogActivity.this)
                        .hasBlurBg(true)
                        .asConfirm("取消服务", "当前设备已经处于服务状态，是否取消洗宠服务，一旦点击确定，将停止洗宠并开门。但是不会退还支付款，请谨慎操作。", "取消", "确定", new OnConfirmListener() {
                            @Override
                            public void onConfirm() {
                                refundFlag=false;
                                exceType="021";
                                exceMark="客户主动点击了停止洗宠操作";
                                sendMechineExption("主动停止洗狗");
                                //点击了确定，将停止服务。
                                ToastUtils.toast(DogActivity.this, "你点击了停止服务");
                                if (dryThread!=null){
                                    dryThread.interrupt();
                                }
                            }
                        }, new OnCancelListener() {
                            @Override
                            public void onCancel() {
                                // 点击了取消，继续服务
                                Log.e(TAG, "onCancel: 点击了取消操作，继续进行洗狗" );
                            }
                        }, false).show();

            }
        });

        findViewById(R.id.qrcode_iv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                oneKeyWash();
            }
        });

//        quickWashTv.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                washContent="一键洗狗";
//                showPayOneDialog();
//                if (codeOneAliv!=null){
//                    codeOneAliv.setVisibility(View.VISIBLE);
//                    codeOneAliv.smoothToShow();
//                }
//
////                PayList payObject=new PayList();
////                payObject.setid(1L);
////                payObject.setPrice(0.01);
////                payObject.setNum(1L);
////                payObject.setGoodsName("一键速洗");
////                PayList[] payLists =new PayList[1];
////                payLists[0] = payObject;
////                PayValue payValue =new PayValue();
////                payValue.setList(payLists);
////                payValue.setWashType("QUICKWASH");
////                HttpPayBean httpPayBean=new HttpPayBean();
////                httpPayBean.setValue(payValue);
////                httpPayBean.setUpTime("2021-11-17 09:35:40");
//
//                getPayUrl(DogWashType.ONEKEYWASH);
////                startToBash(DogBoxType.DRY);
////                try {
////                    Thread.sleep(1000);
////                } catch (InterruptedException e) {
////                    throw new RuntimeException(e);
////                }
////                dryThread.interrupt();
////                Log.e("TAG", "onClick: 操作了线程终端" );
//            }
//        });

//        detailWashTv.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                washContent="高端洗狗";
//                showPayDialog();
//
//
//                getPayUrl(DogWashType.DETAILWASH);
//
//            }
//        });

//        shopTv.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//            }
//        });

//        findViewById(R.id.version_iv).setOnClickListener(new View.OnClickListener(){
//            @Override
//            public void onClick(View view) {
//               existFullscreenAds();
//            }
//        });
    }

    @Override
    public void initData() {
        super.initData();

        if (mTelephonyManager!=null)
            mTelephonyManager.listen(mListener, PhoneStatListener.LISTEN_SIGNAL_STRENGTHS);


        threadPoollExcutorUtil = new ThreadPoollExcutorUtil(10);
        threadPoollExcutorUtil.setOnUploadListener(new OnUploadListener() {
            @Override
            public void onThreadProgressChange(int position, int persent) {

            }

            @Override
            public void onThreadFinish(String filePath) {
                //删掉 数据库的
                sqliteManager.delete(filePath);
                String[] types = filePath.split("\\.");
                if (types.length > 1 && "mp4".equals(types[1])) {
                    //说明是历史mp4文件，不删除
                    Log.i(TAG, "onThreadFinish: 上传后-不删除，我是mp4");
                } else {
                    //删掉文件夹的
                    File file = new File(filePath);
                    file.delete();
                }
                Log.i(TAG, "onThreadFinish: 上传后-删除" + filePath);

            }

            @Override
            public void onThreadInterrupted(int persent) {

                Log.i(TAG, "开机 onThreadInterrupted:当前下载的百分比为 " + persent);

                if (persent == 0 || persent == 100) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showPersentTv.setVisibility(View.INVISIBLE);
                        }
                    });

                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showPersentTv.setVisibility(View.VISIBLE);
                            showPersentTv.setText(persent + "%");
                        }
                    });

                }
            }

            @Override
            public void onAllSuccess(boolean flag, String md5) {
                if (flag) {
                    Log.i(TAG, "onAllSuccess: 单个文件上传成功或者未上传成功");
                } else {
                    Log.i(TAG, "onAllSuccess: 分片上传成功" + md5);
                    merge(md5);
                    sqlInt = 30;
                }
                isNotUpload = true;

//                Log.i("tiwolf", "onAllSuccess: 全部运行完了，下一个任务" );

            }

            @Override
            public void onAllFailed() {
                isNotUpload = true;
            }

            @Override
            public void onDownloadFail() {
                Log.i(TAG, "onDownloadFail: 下载失败");
//                isNotUpload=true;
                isdownloadInt=60;
                isdownloadFlag = true;
            }

            @Override
            public void onDownloadSuccess() {
                Log.i(TAG, "onDownloadSuccess: 下载成功");
                //做一个提示，如果当前处于空闲状态，则查一下列表，看是否有播放的时段，如果有，则去获取列表进行播放 "008"
                android.util.Log.e(TAG, "onDownloadSuccess: 判断广告是否空闲标志isInFreeAdFlag="+isInFreeAdFlag);
                setFreeAdDo();


                isdownloadFlag = true;
                setUploadFile("2");
            }

            @Override
            public void onDownloadTreadSuccess() {
            }

            @Override
            public void onDownloadPackageSuccess() {
                VersionUtil.startToUpdateVersion(sdPath,pversion,DogActivity.this);

            }

            @Override
            public void onDownloadPackageFail() {
                Log.i(TAG, "downloadFailed: 下载超时,重新开始下载");
                //不用这个看下，因为已经有断网重连
                if (pversion != null) {
                    getVerParams().clear();
                    verParams= VersionUtil.startToUpdate(pversion,DogActivity.this);
                    if (verParams!=null){
                        handler.sendEmptyMessage(VERSIONKEY);
                    }
                }
            }

            @Override
            public void onDownloadError(int errorCode) {
                //在这里进行错误检查判断
                isdownloadFlag=true;
                if (errorCode==1){
                    //说明设备io口出现问题
                    Log.i(TAG, "onDownloadError: tfcard出现ioError" );
                    setTFcardErrorWarning(1);
                }else if (errorCode==2){
                    //说明这个是socket的超时导致
                    //让程序延时60次再去下载文件
                    isdownloadInt=5*60;
                }

            }

            @Override
            public void onBoardProgressChange(int persent) {
                Log.i(TAG, "开机 onThreadInterrupted:当前下载的百分比为 " + persent);

                if (persent == 0 || persent == 100) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showPersentTv.setVisibility(View.INVISIBLE);
                        }
                    });

                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showPersentTv.setVisibility(View.VISIBLE);
                            showPersentTv.setTextColor(Color.GREEN);
                            showPersentTv.setText(persent + "%");
                        }
                    });

                }
            }

            @Override
            public void onBoardDownloadSuccess() {
                VersionUtil.startToUpdateVersion(sdPath,lBoardVersion,DogActivity.this,Build.MODEL);
            }

            @Override
            public void onBoardDownloadFail() {
                Log.i(TAG, "downloadFailed: 下载超时,重新开始下载");
                //不用这个看下，因为已经有断网重连
                if (lBoardVersion != null) {
                    getVerParams().clear();
                    verParams=VersionUtil.startToUpdate(lBoardVersion,DogActivity.this,Build.MODEL);
                    if (verParams!=null){
                        handler.sendEmptyMessage(VERSIONKEY);
                    }
                }
            }

            @Override
            public void onUploadsPolieceSuccess(UploadItem uploadItem) {
                isNotUpload = true;

                Log.i(TAG, "onUploadsPolieceSuccess: 将报警文件上传了之后"+uploadItem );
                if (uploadItem!=null){
                    //还未删除上传表格的记录，会一直死循环
                    sqliteManager.deleteByMd5(uploadItem.getMd5());
//                    policeMap.clear();
//                    policeMap.put("alarmTime", uploadItem.getLastModifiedTime());
//                    policeMap.put("pictureMd5", uploadItem.getMd5());
//                    policeMap.put("sn", SocketService.CLIENTID);
//                    handler.sendEmptyMessage(POLICEPITUREUPDATE);
                    Date date = TimeUtil.StrToDateNone(uploadItem.getLastModifiedTime());
                    String str = TimeUtil.DateToStr(date);//将时间转成yyyy-MM-dd HH:mm:ss格式
                    String filePath=uploadItem.getFilePath();
                    int netType=0;
                    if (filePath.contains("_A_")){
                        netType=1;
                    }else if (filePath.contains("_D_")){
                        netType=2;
                    }else if (filePath.contains("_E_")){
                        netType=3;
                    }else if (filePath.contains("_C_")){
                        netType=4;
                    }
                    uploadPoliceRecord(str,uploadItem.getMd5(),netType);
                }
            }

            @Override
            public void onUploadsRecordSuccess(UploadItem uploadItem) {
                isNotUpload = true;

                if (uploadItem != null && uploadItem.getOriginName() != null) {
                    //上传成功后需要删除当前上传的记录
                    sqliteManager.deleteByMd5(uploadItem.getMd5());

                    //上传当前文件记录,开始上传文件记录
//                    Message message1 = handler.obtainMessage();
//                    message1.what = RECORDUPLOAD;
//                    message1.obj = uploadItem.getOriginName() + "," + uploadItem.getMd5();
//                    handler.sendMessage(message1);
                }
            }

            @Override
            public void onUploadPartSuccess(UploadItem uploadItem) {
                isNotUpload = true;
                //上传成功后需要删除当前上传的记录

                String partPath=uploadItem.getFilePath();
                Log.i(TAG, "onUploadPartSuccess: post上传分片成功="+uploadItem.getFilePath() );
                Log.i(TAG, "threadPoolUploadFile run: post上传分片成功"+uploadItem.getChunkIndex()+";数量="+uploadItem.getChunkNumber()+";尾缀="+uploadItem.getExt() );
                sqliteManager.delete(partPath);

                int index=partPath.indexOf("part");
                String filePath=partPath.substring(0,index)+"."+uploadItem.getExt();
                Log.i(TAG, "onUploadPartSuccess: post上传分片成功后，使用这个路径去更新="+filePath );
                // 这个是lastModifiedTime 和 md5 合并了
                String flag=sqliteManager.handleUploadPartFile(filePath);
                if (flag!=null){
                    //进行合并开始
                    merge(uploadItem.getMd5(),uploadItem.getOriginName());
                }

            }

            @Override
            public void onUpLoadInterrupted() {
                isNotUpload=true;
                sqlInt=30;
            }

            @Override
            public void onUploadError() {
                isNotUpload=true;
                sqlInt=30;
            }

            @Override
            public void onFileError() {
                sqlInt=30;
            }
        });

        isConnectIsNormal();

        startUploadWorker();
        startReceiveWorker();
        startAdVertWorker();
        startDogThread();
        startDogWork();
        startListenNet();
    }

    private void setFreeAdDo(){
        if (isInFreeAdFlag){
            //去检查当前是否需要播放广告，因为有网络，所以默认其时间是正常的
            android.util.Log.i(TAG, "在定时巡查中发现有设备没有播放广告，在这里进行播放" );
            //还是去数据库查询一下，以确认它是有列表的。以避免出现更多的数据操作
            cacheLinkedDeque1.add("008");
            synchronized (receiveObject) {
                receiveObject.notifyAll();
            }

        }
    }

    private void startUploadWorker(){
        upLoadWorker = new Thread(new Runnable() {
            @Override
            public void run() {
                Log.i(TAG, "上传的线程: " + upLoadWorker.getName());
                while (!Thread.interrupted()) {
                    while (!cacheLinkedDeque.isEmpty()) {
                        String poll = cacheLinkedDeque.poll();
                        try {
                            threadPoolUploadFile(poll);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    //Waiting for next file
                    synchronized (uploadLock) {
                        try {
                            //isEmpty() may take some time,so we set timeout to detect next file
                            uploadLock.wait(200);
                        } catch (InterruptedException e) {
//                        e.printStackTrace();
                            upLoadWorker.interrupt();
                        }
                    }

                }


            }
        });
        upLoadWorker.start();
    }

    private void startReceiveWorker(){
        ReceiveWorker = new Thread(new Runnable() {
            @Override
            public void run() {
                Log.i(TAG, "接收数据的线程= " + ReceiveWorker.getName());
                while (!Thread.interrupted()) {
                    while (!cacheLinkedDeque1.isEmpty()) {
                        String msg = cacheLinkedDeque1.poll();
                        try {
                            receiveWork(msg);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    //Waiting for next file
                    synchronized (receiveObject) {
                        try {
                            //isEmpty() may take some time,so we set timeout to detect next file
                            receiveObject.wait(200);
                        } catch (InterruptedException e) {
//                        e.printStackTrace();
                            ReceiveWorker.interrupt();
                        }
                    }
                }


            }
        });
        ReceiveWorker.start();
    }

    private void startAdVertWorker(){
        AdVertWorker=new Thread(new Runnable() {
            @Override
            public void run() {
                while (!Thread.interrupted()) {
                    while (!adcacheLinkedDeque.isEmpty()) {
                        List<AlarmBean> alarmBeanList = adcacheLinkedDeque.poll();
                        try {
                            sendMsgToActivity(ActivityConfig.syncadvert,alarmBeanList);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    //Waiting for next file
                    synchronized (advertObject) {
                        try {
                            //isEmpty() may take some time,so we set timeout to detect next file
                            advertObject.wait(200);
                        } catch (InterruptedException e) {
//                        e.printStackTrace();
                            AdVertWorker.interrupt();
                        }
                    }

                }


            }
        });
        AdVertWorker.start();
    }

    private void startDogThread(){
        dogThread=new Thread(new Runnable() {
            @Override
            public void run() {
                while (!Thread.interrupted()) {
                    while (!dogLinkedDeque.isEmpty()) {
                        DogEventBean dogEventBean = dogLinkedDeque.poll();
                        dogEventHandler(dogEventBean.getOrder(),dogEventBean.getHandThing());
                    }

                    //Waiting for next file
                    synchronized (dogObject) {
                        try {
                            //isEmpty() may take some time,so we set timeout to detect next file
                            dogObject.wait(200);
                        } catch (InterruptedException e) {
//                        e.printStackTrace();
                            dogThread.interrupt();
                        }
                    }
                }


            }
        });
        dogThread.start();
    }

    private void receiveWork(String msg) {
        String message=null;
        String order=null;
        if (msg.length()>3){
            message = msg.substring(3);
            order=msg.substring(0,3);
        }else {
            order=msg;
        }

        switch (order){
            case "001":{

                /**
                 * 接收广告闹钟数据，处理下载，定时广告  拿到全部列表->取出当前列表->播放
                 */
                isNullFlag = false;
                boolean isOnPlay = false;//这个是广告播放的标志，是为了解除当前在播放上一个列表，
                // 但是我把时间段把当前播放的时间段设置为空闲广告的时候

                try {
                    Log.i(TAG, "receiveWork:广告收到消息获取到的 " + message);
//                        JSONObject jsonObject=new JSONObject(receiveContent.substring(2));
                    List<AlarmBean> alarmBeanList = new Gson().fromJson(message, new TypeToken<List<AlarmBean>>() {
                    }.getType());
//                    Log.i(TAG, "receiveWork: 当前获取广告列表"+alarmBeanList.size());
                    //获取上一次闹钟列表的数量
                    int lastAlarmSize = PreferenceUtil.getInt(PreferenceUtil.ALARMSIZE, 0);

                    //先关掉全部闹钟
                    for (int i = 0; i < lastAlarmSize; i++) {

                        int lastStartInt = PreferenceUtil.getInt("alarm" + (i * 2 + 1), -1);
                        int lastEndInt = PreferenceUtil.getInt("alarm" + (i * 2 + 2), -1);
                        if (lastStartInt == -1) {
                            //闹钟没有设置过
                        } else {
                            //已经设置过，那么需要将之前设置的闹钟，关掉
                            Intent intent1 = new Intent(DogActivity.this, AlarmReciever.class);
                            intent1.putExtra("_id", lastStartInt);
                            PendingIntent pendingIntent = PendingIntent.getBroadcast(DogActivity.this, lastStartInt, intent1, 0);

                            AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
                            alarmManager.cancel(pendingIntent);
                        }

                        if (lastEndInt == -1) {
                            //闹钟没有设置过
                        } else {
                            //已经设置过，那么需要将之前设置的闹钟，关掉

                            AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);


                            Intent intent2 = new Intent(DogActivity.this, AlarmReciever.class);
                            intent2.putExtra("_id", lastEndInt);
                            PendingIntent pendingIntent = PendingIntent.getBroadcast(DogActivity.this, lastEndInt, intent2, 0);
                            alarmManager.cancel(pendingIntent);

                        }

                    }

                    //直接清空整张表格
                    sqliteManager.clearTable();
                    PreferenceUtil.commitInt(PreferenceUtil.ALARMSIZE, alarmBeanList.size());

                    boolean terminalDoOne = true;

                    //开始设置闹钟
                    for (int i = 0; i < alarmBeanList.size(); i++) {

                        //说明是有的闹钟
                        int alarmId = alarmBeanList.get(i).getId();//获取到闹钟的id
                        String startTime = alarmBeanList.get(i).getStartTime();//获取到闹钟开始的时间
                        String endTime = alarmBeanList.get(i).getEndTime();//获取到闹钟关闭时间
                        int volumn = alarmBeanList.get(i).getVolume();
                        String avTime1 = alarmBeanList.get(i).getTotalDuration();
                        String orderTime = alarmBeanList.get(i).getCurrentTime();
                        String terminal = alarmBeanList.get(i).getIsActive();//是否为终端主动请求，如果是，则为1，如果不是则为0
                        int alarmMode = alarmBeanList.get(i).getPlayMode();//播放模式
                        int playTimes = alarmBeanList.get(i).getTimes();//播放次数
                        List<AlarmPlayBean> downloadBeans = alarmBeanList.get(i).getList();

                        //处理列表里面没有播放列表的情况
                        if (downloadBeans.size() == 0) {
                            continue;
                        }



                        AlarmUtil.alarmPlayer(DogActivity.this,startTime,1,(i * 2 + 1));
                        AlarmUtil.alarmPlayer(DogActivity.this,endTime,1,(i * 2 + 2));


                        String startEnd = startTime + "," + endTime;
                        //设置了之后，保存一下
                        PreferenceUtil.commitInt("alarm" + (i * 2 + 1), i * 2 + 1);
                        PreferenceUtil.commitInt("alarm" + (i * 2 + 2), i * 2 + 2);
                        PreferenceUtil.commitString("alarmTime" + i, startEnd);
//                        Log.i(TAG, "receiveWork: 提交开始闹钟"+(i*2+1));
//                        Log.i(TAG, "receiveWork: 提交结束闹钟"+(i*2+2));
//                        Log.i(TAG, "receiveWork: 提交闹钟列表"+i+";"+startEnd);
//                                }else if (i==1){
//
//                                }

                        //批量添加闹钟数据
//                        sqliteManager.getMdb().beginTransaction();
                        //下面将闹钟alarmId和要播放的文件写入数据库。是否可以将i变成闹钟id，这个是唯一性
                        for (int j = 0; j < downloadBeans.size(); j++) {
                            // 1.先检查是否下载，如果没下载或者数据库没有这个，则去下载。如果下载了，更新数据库播放
                            String md5 = downloadBeans.get(j).getMd5();       //md5
                            int type = downloadBeans.get(j).getType();        //播放类型
                            String ext = downloadBeans.get(j).getExt();       //后缀名
                            String total = downloadBeans.get(j).getSize() + ""; //总长度
                            int downloadId = downloadBeans.get(j).getConfId();//下载id
                            int alarmIds = downloadBeans.get(j).getAdvertId();//闹钟id
                            int duration = downloadBeans.get(j).getDuration();//播放时间
                            int playIndex = downloadBeans.get(j).getSeq();    //播放排序
                            String content = downloadBeans.get(j).getContent();//播放文字
                            String playName=downloadBeans.get(j).getName();     //这个是播放文件的真正名称

                            Log.i(TAG, "receiveWork=: " + md5 + ":" + type + ":" + ext + ":" + total + ":" + downloadId);

                            if (md5 != null) {
                                if (type == 4 || type == 5) {

                                } else {

                                    File file = null;
                                    if (sdPath == null || sdPath.length() == 0) {
                                        file = new File(TestConfig.downloadFilePath + md5 + "." + ext);
                                    } else {
                                        file = new File(sdPath + "/solar/download/" + md5 + "." + ext);
                                    }
//                                    Log.i(TAG, "receiveWork=: "+TestConfig.downloadFilePath+md5+"."+ext);
//                                    Log.i(TAG, "receiveWork=: "+sdPath+"/solar/download/"+md5+"."+ext);
                                    //这里是判断存储之前就有文件的时候
                                    if (file.length() == Integer.valueOf(total)) {
                                        Log.i(TAG, "receiveWork=: 文件已经下载下来了" + md5);

                                    } else {
                                        DownloadItem downloadItem = sqliteManager.downloadIdCheck(md5);

//                                Log.i(TAG, "receiveWork: "+downloadItem.getDownloadExt() );
//                                Log.i(TAG, "receiveWork: "+downloadItem.getPlayType() );
//                                Log.i(TAG, "receiveWork: "+downloadItem.getDownloadId() );
//                                Log.i(TAG, "receiveWork: "+downloadItem.getDownloadFlag() );
//                                Log.i(TAG, "receiveWork: "+downloadItem.getDownloadLength() );
//                                Log.i(TAG, "receiveWork: "+downloadItem.getDownloadName() );
//                                Log.i(TAG, "receiveWork: "+downloadItem.getDownloadTotal() );

                                        //主要查询
                                        if (downloadItem.getDownloadMd5() != null) {

                                        } else {
                                            //如果没有，添加一条
//                                        ContentValues contentValues=new ContentValues();
                                            contentValues.clear();
                                            contentValues.put("downloadMd5", md5);
                                            contentValues.put("downloadLength", "0");
                                            contentValues.put("downloadName", md5 + "." + ext);
                                            contentValues.put("downloadFlag", 1);
                                            contentValues.put("downloadTotal", total);
                                            contentValues.put("downloadId", downloadId);
                                            contentValues.put("playType", type);
                                            contentValues.put("downloadExt", ext);
                                            sqliteManager.addDownLoadItem(contentValues);


                                        }
                                    }

                                }


                                //播放列表直接添加
//                                ContentValues contentValues=new ContentValues();
                                contentValues.clear();
                                contentValues.put("content", content);
                                contentValues.put("downloadMd5", md5);
                                contentValues.put("playExt", ext);
                                contentValues.put("playName", md5 + "." + ext);
                                contentValues.put("playType", type);
                                contentValues.put("downloadTotal", total);
                                contentValues.put("downloadId", downloadId);
                                contentValues.put("playTime", duration);
                                contentValues.put("alarmId", alarmId);
                                contentValues.put("playIndex", playIndex);
                                contentValues.put("alarm1", (i * 2 + 1));
//                                Log.i(TAG, "receiveWork: 直接刷新数据这个alarm1为："+(i*2+1) );
                                contentValues.put("alarm2", (i * 2 + 2));
                                contentValues.put("startTime", startTime);
                                contentValues.put("endTime", endTime);
                                contentValues.put("volumn", volumn);
                                contentValues.put("avTime", avTime1);
                                contentValues.put("mediaName",playName);
                                sqliteManager.addPlayItem(contentValues);

                            }
                        }

                        Log.i(TAG, "receiveWork: 同步请求方式" + terminal + ";" + terminalDoOne);
                        if ("1".equals(terminal) && terminalDoOne) {
                            terminalDoOne = false;
                        }


                        if (isLiveFlag) {
//                            Log.i(TAG, "receiveWork: 广告直接刷新数据==");
                            isOnPlay = true;
                            continue;
                        }


//                        Log.i(TAG, "receiveWork: 广告直接刷新数据"+(i*2+1) );
                        int start = Integer.valueOf(startTime.split(":")[0]) * 60 + Integer.valueOf(startTime.split(":")[1]);
                        int end = Integer.valueOf(endTime.split(":")[0]) * 60 + Integer.valueOf(endTime.split(":")[1]);
//                        Log.i(TAG, "receiveWork: 广告直接刷新数据:startTime:"+startTime );
//                        Log.i(TAG, "receiveWork: 广告直接刷新数据:endTime:"+endTime );
//                        Log.i(TAG, "receiveWork: 广告直接刷新数据:start:"+start );
//                        Log.i(TAG, "receiveWork: 广告直接刷新数据:end:"+end );

                        //直接比较时间戳比较好 直接刷新
                        Date date = new Date();
                        int now = date.getHours() * 60 + date.getMinutes();
//                        Log.i(TAG, "receiveWork: 直接刷新数据:now:"+now );
                        if (now >= start && now < end) {
                            isOnPlay = true;
                            String alarmStr = (i * 2 + 1) + "";
//                            Log.i(TAG, "receiveWork: 直接刷新数据，只有一个开始的:"+alarmStr );
                            ArrayList<PlayItem> playItems1 = sqliteManager.playCheckSingleUrl(alarmStr);
//                            Log.i(TAG, "receiveWork:直接刷新数据 "+playItems1.get(0).getPlayName() );
                            if (playItems1.size() != 0 && playItems1.size() >= 1) {

//                                //这个是关闭指令
                                if (mPlayer != null && mPlayer.isPlaying()) {
                                    mPlayer.stop();
                                    mPlayer.reset();
                                }
                                isPlay = true;
                                isplayIn = false;
                                playInt = -1;


                                Message message1=handler.obtainMessage();
                                message1.what=WARNSHOW;
                                message1.arg1=2;
                                handler.sendMessage(message1);


//                    Log.i(TAG, "Event: 关闭指令" );
                                playItems = null;

                                Thread.sleep(200);

                                playItems = playItems1;
                                playItemBackpackages = playItems1;

                                //开始确认音量值
                                musicVolumn = playItems.get(0).getVolumn();
                                Log.i(TAG, "receiveWork: 从后台返回 开机广告 时的音量" + musicVolumn + ";vv=" + vv.isPlaying() + ";ttp=" + textToSpeech.isSpeaking());

                                if (!vv.isPlaying() && !textToSpeech.isSpeaking()) {
                                    if (isVolumeOn) {
                                        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, fixedVolume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
                                    } else {
                                        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, musicVolumn, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
                                    }

                                    Log.i(TAG, "receiveWork: 0000从后台返回 开机广告 时的音量" + musicVolumn);
                                } else {
                                    currentVolumn = musicVolumn;
                                    Log.i(TAG, "receiveWork: 1111从后台返回 开机广告 时的音量,声音=" + musicVolumn);
                                }
//                                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,musicVolumn,AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);

                                if (isVolumeOn) {
                                    audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, fixedVolume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
                                } else {
                                    audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, musicVolumn, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
                                }




                                isplayIn = true;
                                playInt = 0;

                                isAdvertisement = true;
                                Log.i(TAG, "同步=receiveWork: isLiveFlag=" + isLiveFlag + ";terminal=" + terminal);
                                if (!isLiveFlag) {
                                    playMediaFile();
                                }


                            }

                        }

                    }
                    //如果没有播放时间段，而且
                    if (!isOnPlay) {
                        isPlayOn = false;
                        currentVolumn = 1;//关闭后设置当前音量值，避免出现这个情况：
                        Log.i(TAG, "receiveWork: 2222从后台返回 开机广告 时的音量，声音=" + currentVolumn + ";" + musicVolumn);

                        // 广播播放前是广告，它是按照广告的音量设置，但是当广播播放完之后，
                        // 广告刚刚好在它之前播放完。这样子就会造成闲时广告会使用广告的音量

                        alarmId = -1;

                        PreferenceUtil.commitString("currentNoise", "no");

                        isPlay = true;
                        isplayIn = false;
                        playInt = -1;

                        isAdvertisement=false;
//                    Log.i(TAG, "Event: 关闭指令" );
                        playItems = null;

                        if (!isLiveFlag) {
                            //开机设置闲时音量
                            audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);

                            playMediaFile();
                        }

                    } else {
                        isPlayOn = true;
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            }
            case "005": {

                /**
                 * 下载音视频等各种文件
                 */
                try {
                    Log.i(TAG, "download1:1添加下载资料到数据库 " + message);
                    JSONObject jsonObject = new JSONObject(message);
                    String downloadMd5 = jsonObject.optString("md5");
                    int downloadId = jsonObject.optInt("id");
                    int type = jsonObject.optInt("type");
                    if (type == 4 || type == 5) {

                    } else {
                        boolean isExist = sqliteManager.downloadCheckSingleUrl(downloadMd5);
                        if (isExist) {
//                            setUploadFile(downloadMd5);
                            Log.i(TAG, "threadPoolUploadFile: 七牛云==下载99");
                            //没有下载的情况下才进行下载动作
                            if (isdownloadFlag){
                                qiniuDownloadFile(downloadMd5);
                            }
                        } else {
                            int duration = jsonObject.optInt("duration");
                            String ext = jsonObject.optString("ext");
                            String name = downloadMd5 + "." + ext;
                            String length = jsonObject.optString("size");
//                            ContentValues contentValues=new ContentValues();
                            contentValues.clear();
                            contentValues.put("downloadMd5", downloadMd5);
                            contentValues.put("downloadLength", "0");
                            contentValues.put("downloadName", name);
                            contentValues.put("downloadFlag", 1);
                            contentValues.put("downloadTotal", length);
                            contentValues.put("downloadId", downloadId);
                            contentValues.put("playType", type);
                            contentValues.put("downloadExt", ext);
                            sqliteManager.addDownLoadItem(contentValues);
//                            setUploadFile(downloadMd5);
                            Log.i(TAG, "threadPoolUploadFile: 七牛云==下载1010");
                            if (isdownloadFlag){
                                qiniuDownloadFile(downloadMd5);
                            }
                        }
                    }


                } catch (JSONException e) {
                    e.printStackTrace();
                }

                break;
            }
            case "006": {

                /**
                 * 定时视频进行处理
                 */
                //过了3分钟关闭
                if (cameraFragment != null && canRecordFlag) {
                    canRecordFlag=false;
                    cameraFragment.startRecordMp4();
                }
                break;
            }
            case "007":{

                /**
                 * 定时广告处理
                 */
                //如果是平常广告，就使用平常广告的列表
                playItems = sqliteManager.playCheckSingleUrl(message);
                playItemBackpackages = playItems;

                if (playItems != null && playItems.size() > 0) {
                    for (int i = 0; i < playItems.size(); i++) {
                        Log.i(TAG, "receiveWork: 闹钟获取广告列表" + playItems.get(i).getPlayName());
                    }
                }


                //确保是有播放列表的
                if (playItems != null && playItems.size() > 0) {

                    //开始确认音量值
                    musicVolumn = playItems.get(0).getVolumn();
                    if (!vv.isPlaying() && !textToSpeech.isSpeaking()) {
                        if (isVolumeOn) {
                            audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, fixedVolume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
                        } else {
                            audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, musicVolumn, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
                        }

                    } else {
                        currentVolumn = musicVolumn;
                        Log.i(TAG, "receiveWork: 列表得到时的声音值=" + currentVolumn);
                    }


                    if (Integer.valueOf(message) % 2 == 0) {
                        //在这里设置广告同步为false
                        isAdvertisement = false;
                        currentVolumn = 1;//关闭后设置当前音量值，避免出现这个情况：
                        Log.i(TAG, "receiveWork: 没有列表时候的声音值=" + currentVolumn);
                        // 广播播放前是广告，它是按照广告的音量设置，但是当广播播放完之后，
                        // 广告刚刚好在它之前播放完。这样子就会造成闲时广告会使用广告的音量

                        alarmId = -1;

                        PreferenceUtil.commitString("currentNoise", "no");
                        //这个是关闭指令
                        if (mPlayer != null) {
                            if (mPlayer.isPlaying()) {
                                mPlayer.stop();
                                mPlayer.reset();
                                Log.i(TAG, "receiveWork: 到时间停止播放");
                            }
                        }
                        isPlay = true;
                        isplayIn = false;
                        playInt = -1;


//                    Log.i(TAG, "Event: 关闭指令" );
                        playItems = null;

                        //开机设置闲时音量
                        if (!vv.isPlaying() && !textToSpeech.isSpeaking()) {
                            if (isVolumeOn) {
                                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, fixedVolume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
                            } else {
                                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, freeVolumn, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
                                musicVolumn = freeVolumn;
                            }

                        } else {
                            currentVolumn = freeVolumn;
                            Log.i(TAG, "receiveWork: 没有列表时候111的声音值=" + currentVolumn);
                        }
                        playMediaFile();

                    } else {

                        //获取到alarm，为更新音量做准备
                        alarmId = Integer.valueOf(message);

                        isAdvertisement = true;
                        PreferenceUtil.commitString("currentNoise", message);
                        //这个是开启指令
                        isplayIn = true;
                        isPlayOn = true;
                        Log.i(TAG, "洗狗机播放文件Event: 回来一次" );
                        Log.i(TAG, "洗狗机播放文件Event: " + playItems.get(0).getMediaName());
                        Log.i(TAG, "洗狗机播放文件Event: " + playItems.get(0).getPlayName());
                        Log.i(TAG, "洗狗机播放文件Event: " + playItems.get(0).getDownloadMd5());
                        Log.i(TAG, "洗狗机播放文件Event: " + playItems.get(0).getPlayIndex());
                        Log.i(TAG, "洗狗机播放文件Event: " + playItems.get(0).getPlayExt());
                        Log.i(TAG, "洗狗机播放文件Event: " + playItems.get(0).getDownloadTotal());
                        Log.i(TAG, "洗狗机播放文件Event: " + TestConfig.downloadFilePath + playItems.get(0).getPlayName());
                        Message message1=handler.obtainMessage();
                        message1.what=WARNSHOW;
                        message1.arg1=2;
                        handler.sendMessage(message1);
                        playInt = 0;
                        isNullFlag = false;

                        playMediaFile();
                    }

                }

                break;
            }
            case "008": {

                /**
                 * 开机时 广告，广播初始化处理
                 */
                initPhone();
                break;

            }

            case "010":{
                playMediaFile();
                break;
            }

            case "024":{
                //需要24小时后 再一次定时的
                int value=Integer.valueOf(message);
                AlarmUtil.set24HourRedo(DogActivity.this,value);
                break;
            }

        }

    }

    private synchronized void firstAd(){
        Log.i(TAG, "firstAd: 开机初始化设备广告" );
        if (adverFlag){
            adverFlag=false;
            cacheLinkedDeque1.add("008");
            synchronized (receiveObject) {
                receiveObject.notifyAll();
            }
        }


    }

    boolean washDoorFlag=false;//洗狗过程中，门是否有打开过标志
    /**
     * 每隔两秒钟进来一次
     * @param order
     * @param message
     */
    private void dogEventHandler(String order,String message){

        switch (order){
            case "Z00":{
                //检查水位，检查温度
                if (waterLevelFlag){
                    //如果小于最低温度并且水箱加热阀门没有打开，则需要打开
                    if (waterTem<=lowerWater && !heatingWaterIsOpenFlag){
//                        heatingWaterIsOpenFlag=true;  返回再将其设置成true
                        heatWaterTem=waterTem;
                        heatInt=600;
                        heatFlag=true;
                        sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXWATERHEATINGOPEN);
                    }else if(waterTem>=upperWater && heatingWaterIsOpenFlag){
                        heatFlag=false;
                        sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXWATERHEATINGCLOSE);
                    }else if (waterTem>(upperWater+2)){
                        //防止heatingWaterIsOpenFlag出现没返回或者其他异常的情况 高出最高设置温度2度的情况，说明加热部分没按照规定关闭
                        heatFlag=false;
                        sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXWATERHEATINGCLOSE);
                    }

                    if (onceDoFlag){
                        if (!"正常".equals(dogStateStr)){
                            dogStateStr="正常";
                            Message msg=handler.obtainMessage();
                            msg.obj=dogStateStr;
                            msg.what=DOGDEVICESTATE;
                            handler.sendMessage(msg);
                        }
                    }

                    cancelWaterLevelWarn();

                }else{

                    Log.e(TAG, "dogEventHandler: 水加热是否打开标志="+heatingWaterIsOpenFlag );
                    //马上取消加热指令  出现加热开关取消或者是水温过高的时候，马上进行取消加热 到低水位的时候必须让其发送取消加热一次
                    if (heatingWaterIsOpenFlag || (!"水位过低".equals(dogStateStr))){
                        //发送取消加热指令
                        heatFlag=false;
                        sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXWATERHEATINGCLOSE);
                    } else if (waterTem>(upperWater+2)) {
                        //防止heatingWaterIsOpenFlag出现没返回或者其他异常的情况 高出最高设置温度2度的情况，说明加热部分没按照规定关闭
                        heatFlag=false;
                        sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXWATERHEATINGCLOSE);
                    }

                    if (!"水位过低".equals(dogStateStr)){
                        dogStateStr="水位过低";
                        Message msg=handler.obtainMessage();
                        msg.obj=dogStateStr;
                        msg.what=DOGDEVICESTATE;
                        handler.sendMessage(msg);
                    }
                }

                if (stage>=3 && stage<8){
                    if (waterTem>=50){
                        //在用水的时候出现大于50°，直接跳到异常状态下.在停止洗澡后会跳回stage=100，应该不需要再多加一个flag吧
                        exceMark="在步骤"+stage+"发现水温过高，导致洗宠服务结束";
                        speakDogStateWarn("设备水温过高，已打开舱门，请尽快领走你的爱犬");
                        sendMechineExption("在步骤"+stage+"发现水温过高，导致洗宠服务结束");
                        Log.e(TAG, "dogEventHandler: 在步骤"+stage+"发现水温过高，导致洗宠服务结束" );
                        if (dryThread!=null){
                            dryThread.interrupt();
                        }
                    }

                    //如果洗狗过程中  门被打开了   当前门打开后，直接暂停在当前位置，等程序重新唤醒
//                    if (!doorFlag){
//                        exceMark="在步骤"+stage+"中洗宠门被打开，导致洗宠服务结束";
//                        sendMechineExption("在步骤"+stage+"中洗宠门被打开，导致洗宠服务结束");
//                        speakDogStateWarn("设备洗宠过程中门被打开，已停止洗宠服务。请尽快领走您的爱犬");
//                        Log.e(TAG, "dogEventHandler: 在步骤"+stage+"中洗宠门被打开，导致洗宠服务结束");
//                        if (dryThread!=null){
//                            dryThread.interrupt();
//                        }
//
//                        washDoorFlag=true;
//                    }
//                    else{
//                        //如果门是正常关闭的，那么判断是否洗狗过程中是否有开过
//                        if (washDoorFlag){
//                            //洗狗过程中有开过，那么进行线程唤醒，继续从暂停部分开始工作
////                            dryThread.notify();
//                            washDoorFlag=false;
//
//                        }
//                    }

                }

                if (waterTem>lowerWater){
                    cancelWaterTemWarn();
                }

                if (stage==8){
                    if (houseTem>houseUpper && heatingInvirIsOpenFlag){
                        sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXHEATINGCLOSE);
                    }else if (houseTem<houseLower && !heatingInvirIsOpenFlag){
                        sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXHEATINGOPEN);
                    }
                }else{
                    if (heatingInvirIsOpenFlag){
                        sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXHEATINGCLOSE);
                    }
                }

                if (!urgenFlag){
                    //将之前的状态变为原始状态
                    heatingWaterIsOpenFlag=false;


                    exceType="020";     //急停按钮 按下
                    //弹出紧急按钮对话框
                    if (isUrgenFlagDo){
                        handler.sendEmptyMessage(DOGURGENSHOW);
                        isUrgenFlagDo=false;
                        //紧急按钮被按下
                        if (stage>2 && stage<9){
                            speakDogStateWarn("设备按下了紧急按钮，门锁已打开，请尽快把您的爱宠取出来。");
                            refundFlag=false;
                            exceMark="客户在洗狗过程中按下了洗宠紧急按钮";
                            //说明是在洗狗的过程中
                            if (dryThread!=null){
                                dryThread.interrupt();
                            }
                            sendMechineExption("异常停止");
                        }else if (stage<=2){
                            speakDogStateWarn("设备按下了紧急按钮，门锁已打开，请尽快把您的爱宠取出来。");
                            exceMark="客户在洗狗开始前按下了洗宠紧急按钮";
                            stage=100;
                            handler.sendEmptyMessage(DOGCLOSEDOORDISMISSSHOW);
                            handler.sendEmptyMessage(DOGOPENDOORDISMISSSHOW);
                            refundFlag=true;
                            stopDogWash();
                            sendMechineExption("异常停止");
                        }else if(stage>=11 && stage<=14){
                            speakDogStateWarn("设备按下了紧急按钮，门锁已打开");
                            if (disinfectionThread!=null){
                                disinfectionThread.interrupt();
                            }
                        }else{
                            exceMark="客户按下了洗宠紧急按钮";
                            speakDogStateWarn("设备按下了紧急按钮，门锁已打开");
                            sendMechineExption("异常停止");
                        }
                    }
                    stage=101;
                }else{
                    // 急停按钮 拉起
                    //关闭紧急按钮对话框
                    if (!isUrgenFlagDo){
                        isUrgenFlagDo=true;
                        handler.sendEmptyMessage(DOGURGENDISMISS);
                    }
                }


                // 这里的stage决定了会不会反复关门
                if (stage==1){
                    //说明在第一阶段门已经打开，需要不断的监测 接近开关是否关闭。如果
                    if (!touchSwitchFlag){
                        //说明程序已经让门去打开，现在需要判断接触开关是否没接触  没接触-->相当于人将门拉开了
                        if (!doorFlag){
                            //门已经打开
                            speakDogStateWarn("设备舱门已经打开，请尽快把您的爱宠放进来");
                            touchSwitchFlag=true;
                            setCloseDoorWarn("您的爱宠放进去之后，请把门关好。我们准备给您的爱宠洗澡啦");
                            try {
                                Thread.sleep(5000);     //延时5秒，防止手抖导致的误关
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }else{
                        //说明程序已经让门去关闭，现在需要判断接触开关是否接触  接触-->相当于人将门关闭
                        if (doorFlag){
                            // 门已经关闭 需要发指令上锁  关门指令之后马上进入stage=2流程
                            sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXCLOSEDOOR);
                        }
                    }
                }else if (stage==2){
                    if (!waterLevelFlag){
                        //如果水位过低，则先等等
                        Log.e(TAG, "dogEventHandler: 水位过低，在等待中。。。" );
                        exceType="002";
                        exceMark="在流程中水位过低";
                        //报异常
                        sendMechineExption("在第一次清水清洗中出现水位过低");

                    }else{
                        if (waterTem<lowerWater){
                            //如果水温过低，则先等等
                            Log.e(TAG, "dogEventHandler: 水温过低，在加热中，请稍等。。。" );
                        }else{
                            startToBash();
                        }
                    }
                }else if (stage>2 && stage<=5){
                    if (!waterLevelFlag){
                        exceType="00"+stage;
                        exceMark="在流程中"+stage+"水位过低";
                        //报异常
                        sendMechineExption("在步骤"+stage+"中出现水位过低");
                        speakDogStateWarn("尊敬的客户，当前设备在清洗过程中出现水位过低异常，准备停止洗狗程序。请准备取走您的爱犬，支付款将会原路退回");
                        Log.e(TAG, "dogEventHandler: 在步骤"+stage+"中出现水位过低,停止洗狗，返回付款");
                        refundFlag=true;
                        if (dryThread!=null){
                            dryThread.interrupt();
                        }

                    }
                }else if (stage>5 && stage<=8){
                    if (!waterLevelFlag){
                        exceType="00"+stage;
                        exceMark="在流程中"+stage+"水位过低";
                        //报异常
                        sendMechineExption("在步骤"+stage+"中出现水位过低");
                        refundFlag=false;

                    }
                }else if (stage==9){
                    //说明在第一阶段门已经打开，需要不断的监测 接近开关是否关闭。如果
                    if (!touchSwitchFlag){
                        //说明程序已经让门去打开，现在需要判断接触开关是否没接触  没接触-->相当于人将门拉开了
                        if (!doorFlag){
                            //门已经打开
                            speakDogStateWarn("将您的爱宠取出来之后，麻烦把门关闭。我们需要给洗澡舱消毒，谢谢！");
                            touchSwitchFlag=true;
                            handler.sendEmptyMessage(DOGOPENDOORDISMISSSHOW);
                            setCloseDoorWarn("您的爱宠出来之后，请把门关好，谢谢。下一步是消毒，请一定不要将您的爱宠放在里面！");
                            try {
                                Thread.sleep(5000);     //延时5秒，防止手抖导致的误关
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }else{
                        //说明程序已经让门去关闭，现在需要判断接触开关是否接触  接触-->相当于人将门关闭
                        if (doorFlag){
                            // 门已经关闭 需要发指令上锁  关门指令之后马上进入stage=10流程
                            sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXCLOSEDOOR1);//关门
//                            try {
//                                Thread.sleep(100);
//                            } catch (InterruptedException e) {
//                                throw new RuntimeException(e);
//                            }
//                            sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXLIGHTCLOSE);//关闭内照明
                        }
                    }
                }else if (stage==100){
                    Log.e(TAG, "dogEventHandler: 异常状态");
                    //说明在异常阶段
                    if (!touchSwitchFlag){
                        //说明程序已经让门去打开，现在需要判断接触开关是否没接触  没接触-->相当于人将门拉开了
                        if (!doorFlag){
                            //门已经打开
                            handler.sendEmptyMessage(DOGOPENDOORDISMISSSHOW);//将门打开的弹窗关掉
                            speakDogStateWarn("设备舱门已经打开，请尽快将您的爱宠带出来");
                            touchSwitchFlag=true;
                            setCloseDoorWarn("您的爱宠取出来后，麻烦把门重新关闭。谢谢！");
                            try {
                                Thread.sleep(5000);     //延时5秒，防止手抖导致的误关
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }else{
                        Log.e(TAG, "dogEventHandler: 异常状态的关门="+touchSwitchFlag+";doorFlag="+doorFlag);
                        //说明程序已经处于关门阶段
                        if (doorFlag){
                            stage=101;//让它后面不进来
                            sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXCLOSEDOOR2);
                        }
                    }

                }

                break;
            }
        }
    }

    private void setMechineWaterLevelWarn(String warn){
        waterlevelView=new XPopup.Builder(DogActivity.this).asCustom(new WarnPopup(DogActivity.this,warn));
        waterlevelView.show();
    }

    private void cancelWaterLevelWarn(){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (waterlevelView!=null){
                    waterlevelView.dismiss();
                    waterlevelView=null;
                }
            }
        });

    }

    private void setMechineWaterTemWarn(String warn){
        temlevelView=new XPopup.Builder(DogActivity.this).asCustom(new WarnTemPopup(DogActivity.this,warn));
        temlevelView.show();
    }

    private void cancelWaterTemWarn(){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (temlevelView!=null){
                    temlevelView.dismiss();
                    temlevelView=null;
                }
            }
        });

    }

    private void sendMechineOrders(String order){
        if (mSocketService!=null && urgenFlag){
            mSocketService.sendMechineOrder(order);
        }
    }

    private void sendMechineExption(String exption){
        if (mSocketService!=null){
            mSocketService.clearSerialList();
        }

        handler.sendEmptyMessage(DOGEXCEPTIONUPLOAD);
        //上传异常给服务器
    }

    private synchronized void initPhone(){

        Log.i(TAG, "receiveWork: 可以跳回播放音频"+isHasLiveFlag);
        if (isHasLiveFlag) {
            isHasLiveFlag = false;//只有智能ai结束后或者是开机第一次才会进来查询
            //如果是直播开关打开，那么检查直播列表，如果列表中有当前时间段播放的，那么进行直播，如果没有，那么进行广告初始化,将isLiveFlag设置成false。但是不放进偏好设置，下次进来要重新确认这个
            //初始化设备，会先检查直播，然后再检查广告
//                    rebootMechine("4:50");
            //去数据库获取直播列表 liveList
            ArrayList<LiveBean> liveList = sqliteManager.getTabList();

            try {
                //检查当前有没有播放的时间段
                if (liveList != null && liveList.size() > 0) {
                    for (int j = 0; j < liveList.size(); j++) {
                        String startStr = liveList.get(j).getStartTime();
                        String endStr = liveList.get(j).getEndTime();
                        int id = liveList.get(j).getPlayId();
                        String url = liveList.get(j).getUrl();
                        String orderTime = liveList.get(j).getDoTime();
                        int volume = liveList.get(j).getVolume();
                        if (volume == 0) {
                            volume = 15;
                        }
                        Log.i(TAG, "receiveWork: 开机直播获取时间=" + startStr);
                        Log.i(TAG, "receiveWork: 开机直播获取路径=" + url);

                        //进行时间定时
                        Calendar startCalendar = AlarmUtil.getCaledar(startStr, 0);
                        AlarmUtil.startAlarm(DogActivity.this, startCalendar, j * 2 + 501);
                        Calendar endCalendar = AlarmUtil.getCaledar(endStr, 0);
                        AlarmUtil.startAlarm(DogActivity.this, endCalendar, j * 2 + 502);


                        long startLo = AlarmUtil.getCurrentCaledar(startStr, 0).getTimeInMillis();
                        long endLo = AlarmUtil.getCurrentCaledar(endStr, 0).getTimeInMillis();
                        long orderLo = System.currentTimeMillis();
                        if ((startLo > endLo && orderLo > startLo && orderLo < endCalendar.getTimeInMillis()) || (orderLo > startLo && orderLo < endLo)) {
                            isLiveFlag = true;
                            isInFreeAdFlag=false;
                            Log.i(TAG, "receiveWork: 直播的标志000=" + isLiveFlag);
                            //如果有播放时间段，那么开始播放
                            if (url != null && url.length()>4 && (url.startsWith("http") || url.startsWith("rtmp"))) {

                                Message message=handler.obtainMessage();
                                message.obj=url;
                                message.what=LIVEAD;
                                handler.sendMessage(message);
                            }else{
                                isLiveFlag = false;
                                isInFreeAdFlag=true;
                            }
                            break;
                        } else {
                            isLiveFlag = false;
                            isInFreeAdFlag=true;
                        }
                    }
                } else {
                    isLiveFlag = false;
                    isInFreeAdFlag=true;
                }
            } catch (Exception e) {
                e.printStackTrace();
                isLiveFlag = false;
                isInFreeAdFlag=true;
                Log.i(TAG, "receiveWork: " + e.getLocalizedMessage());
            }


        } else {
            //如果直播关闭，那么进行广告初始化 这个是定时过来的。不用管

        }
        if (isLiveFlag) {
            isAdvertisement = false;
            return;
        }
        //这些应该都是在有网络的时候再开始,只要时间正确就可以开始了
        Log.i(TAG, "receiveWork: 开机广告广播处理");


        if (playItems != null && playItems.size() > 0 && mPlayer != null && mPlayer.isPlaying()) {
            //说明正在播放广告
            currentVolumn = 1;//关闭后设置当前音量值，避免出现这个情况：
            Log.i(TAG, "receiveWork: 没有列表时候2222的声音值=" + currentVolumn);
            // 广播播放前是广告，它是按照广告的音量设置，但是当广播播放完之后，

            isPlay = true;
            isplayIn = false;
            playInt = -1;

            Message message1=handler.obtainMessage();
            message1.what=WARNSHOW;
            message1.arg1=2;
            handler.sendMessage(message1);

//                    Log.i(TAG, "Event: 关闭指令" );
            playItems = null;

        }

        isNullFlag = false;


        //普通广告使用

        /**
         * 获取闹钟列表   计算播报时间，定时闹钟
         * 播放广告
         */
        advert();


    }

    /**
     * 普通广告列表播放和闲时
     */
    private void advert(){

        Log.i(TAG, "receiveWork: 开机广告 普通广告");
        int alarmSize = PreferenceUtil.getInt(PreferenceUtil.ALARMSIZE, 0);
        Log.i(TAG, "receiveWork: 开机广告 进来到611普通广告:" + alarmSize);
        if (alarmSize > 0) {
            boolean isHasPeriod = false;
            for (int i = 0; i < alarmSize; i++) {


                int startInt = PreferenceUtil.getInt("alarm" + (i * 2 + 1), -1);
                int endInt = PreferenceUtil.getInt("alarm" + (i * 2 + 2), -1);
                String startEnd = PreferenceUtil.getString("alarmTime" + i, "no");
//                                Log.i(TAG, "receiveWork: "+startInt );
//                                Log.i(TAG, "receiveWork: "+startEnd );
                //看是否有处于时间段内的闹钟，有则播放相关列表
                if (!"no".equals(startEnd)) {
                    String startTime = startEnd.split(",")[0];
                    String endTime = startEnd.split(",")[1];
                    //最新更改，2020.4.16 如果不加这个判断，则会出现isPlayInt后面的false会覆盖掉前面的ture
                    if (!isHasPeriod) {
                        int start = Integer.valueOf(startTime.split(":")[0]) * 60 + Integer.valueOf(startTime.split(":")[1]);
                        int end = Integer.valueOf(endTime.split(":")[0]) * 60 + Integer.valueOf(endTime.split(":")[1]);


                        //直接比较时间戳比较好
                        Date date = new Date();
                        int now = date.getHours() * 60 + date.getMinutes();
//                                        Log.i(TAG, "receiveWork 当前时间: "+now );
//                                        Log.i(TAG, "receiveWork: 开始时间："+start );
//                                        Log.i(TAG, "receiveWork: 结束时间："+end );

                        if (now >= start && now < end) {
                            if (mPlayer != null && mPlayer.isPlaying()) {
                                mPlayer.stop();
                                mPlayer.reset();
                            }

                            playInt = 0;
                            playItems = sqliteManager.playCheckSingleUrl("" + startInt);
//                                            Log.i(TAG, "receiveWork: 当前的队列为"+playItems.size() );
                            playItemBackpackages = playItems;
                            isPlayOn = true;
                            //说明可以播放
                            if (playItems.size() >= 1) {

                                //获取到alarm，为更新音量做准备
                                alarmId = startInt;

                                //开始确认音量值
                                musicVolumn = playItems.get(0).getVolumn();
                                Log.i(TAG, "receiveWork: 开机广告 时的音量" + musicVolumn + ";video正在播放？=" + vv.isPlaying() + ";文本正在播放？=" + textToSpeech.isSpeaking());
                                if (vv.isPlaying() || textToSpeech.isSpeaking()) {
//                                                    Log.i(TAG, "receiveWork: 开机设置音量"+musicVolumn);
                                    currentVolumn = musicVolumn;
                                    Log.i(TAG, "receiveWork: 播放其他保留当前声音111=" + currentVolumn);
                                } else {
//                                                    Log.i(TAG, "receiveWork: 开机设置音量111"+musicVolumn);
                                    if (isVolumeOn) {
                                        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, fixedVolume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
                                    } else {
                                        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, musicVolumn, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
                                    }

                                }

                                isAdvertisement = true;
                                isplayIn = true;
                                playMediaFile();

                                isHasPeriod = true;
                            }

                        }
                    }


                    //对列表重新定义一次闹钟，这个主要是因为断电之后，闹钟将会全部清零。所以需要重新配置
                    AlarmUtil.alarmPlayer(DogActivity.this,startTime,1,(i * 2 + 1));
                    AlarmUtil.alarmPlayer(DogActivity.this,endTime,0,(i * 2 + 2));

                }


            }

            if (!isHasPeriod) {
                //开机设置闲时音量
                if (!vv.isPlaying() && !textToSpeech.isSpeaking()) {
                    if (isVolumeOn) {
                        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, fixedVolume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
                    } else {
                        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, freeVolumn, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
                        musicVolumn = freeVolumn;
                    }

                } else {
                    currentVolumn = freeVolumn;
                    Log.i(TAG, "receiveWork: 闲时声音111=" + currentVolumn);
                }
                isplayIn = false;
                isPlay=true;
//                            playMediaFile(playInt);
                Message message1 = handler.obtainMessage();
                message1.what = FREEADV;
                handler.sendMessage(message1);
            }

        } else {
            //回到空闲播放
            Message message1 = handler.obtainMessage();
            message1.what = FREEADV;
            handler.sendMessage(message1);
        }
    }


    //进行退款
    private void refundMoney(){
        handler.sendEmptyMessage(DOGREFUNDPAY);
    }

    private void stopDogWash(){
        Log.e(TAG, "stopDogWash: 洗狗线程停止后，需要对洗狗机进行退款"+refundFlag );
        //上传异常信息
        if (refundFlag){
            refundMoney();//退钱
        }
        //线程停止后，进行退款
//        sendMechineExption("异常停止");
        if (stage==3 || stage==5 || stage==7){
            sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXWATERCLOSE);
            sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXWATERPUMPCLOSE);
        }else if (stage==4){
            sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXWASHCLOSE);
            sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXCONCENTRATEDCLOSE);
            sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXWATERPUMPCLOSE);
        }else if (stage==6){
            sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXCONDITIONERCLOSE);
            sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXCONCENTRATEDCLOSE);
            sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXWATERPUMPCLOSE);
        }else if (stage==8){
            sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXHAIRDRYERCLOSE);
            sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXHEATINGCLOSE);
            sendMechineOrders(SerialConfigUtil.SendHex26);
        }
        sendFlowNum(9);//变回开始界面
        sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXOPENDOOR2);
        sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXLIGHTCLOSE);//关闭内照明
        setFlowMsg("空闲",0);
        Log.e(TAG, "stopDogWash: 洗狗线程停止后，需要对洗狗机进行退款1111111111111111111111" );
    }

    private void stopDogDisinfectant(){
        Log.e(TAG, "stopDogWash: 洗狗线程停止后，已经到了消毒流程" );
        exceType="022";     //消毒过程中出现了异常情况
        exceMark="消毒出现了异常情况";
        sendMechineExption("在消毒流程出现异常停止");
        handler.sendEmptyMessage(DISINFECTANTSDISMISS);
        if (stage==13){
            sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXWATERCLOSE);
            sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXWATERPUMPCLOSE);
        }else if(stage==12){
            sendMechineOrders(SerialConfigUtil.SendHex26);
        }else if (stage==11){
            sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXDISINFECTANTCLOSE);
            sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXWATERPUMPCLOSE);  //关高压水泵
        }
        sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXOPENDOOR2);
        sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXLIGHTCLOSE);//关闭内照明
        setFlowMsg("空闲",0);
        Log.e(TAG, "stopDogWash: 消毒线程停止后，不需要进行退款行为" );
    }

    private synchronized void getPayUrl(DogWashType dogWashType){
        if (token!=null){
            HttpPayBean httpPayBean=new HttpPayBean();
            if (dogWashType==DogWashType.ONEKEYWASH){
                PayList payObject=new PayList();
                payObject.setid(1L);
                payObject.setPrice(oneKeyWashPrice);
                payObject.setNum(1L);
                payObject.setGoodsName("一键速洗");
                PayList[] payLists =new PayList[1];
                payLists[0] = payObject;
                PayValue payValue =new PayValue();
                payValue.setList(payLists);
                payValue.setSn(FlyUtil.getSn(DogActivity.this));
                payValue.setWashType("QUICKWASH");
                httpPayBean.setValue(payValue);
                String now= DateUtil.now();
                httpPayBean.setUpTime(now);
            }else{
                PayList payObject=new PayList();
                payObject.setid(1L);
                payObject.setPrice(totalMoney);
                payObject.setNum(1L);
                payObject.setGoodsName("高端精洗");
                PayList[] payLists =new PayList[1];
                payLists[0] = payObject;
                PayValue payValue =new PayValue();
                payValue.setList(payLists);
                payValue.setSn(FlyUtil.getSn(DogActivity.this));
                payValue.setBodyFeature(dogTypeStr);
                payValue.setHairFeature(hairLongStr);
                payValue.setTickFeature(hairLessStr);
                payValue.setWashType(washTypeStr);
                httpPayBean.setValue(payValue);
                String now= DateUtil.now();
                httpPayBean.setUpTime(now);
            }


            mPresenter.orderPay(httpPayBean,token);
        }


    }



    /**
     * 开始进行洗狗动作  只能出现这一个洗澡的流程
     */
    private synchronized void startToBash(){
        if (stage==3){
            return;
        }
        stage=3;
        dryThread=new Thread(new Runnable() {
            @Override
            public void run() {
                try {
//                    stage=3;
                    Log.e("TAG", "run: 洗狗机洗澡开始" );
                    if (DogBoxType.DRY!=dogBoxType){
                        //如果是烘干，跳过洗澡环节
                        long num= (long) (oneWaterInt*totalMul);
                        setWashDown(num+stepInterval,stepTv,1);
                        setFlowMsg("洗狗中(第一次清水冲洗)",num+stepInterval);
                        //开始第一次喷水清洗
                        sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXWATEROPEN);  //开水阀
                        Thread.sleep(100);
                        sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXWATERPUMPOPEN);  //开高压水泵
//                        Thread.sleep((long)(oneWaterInt*totalMul));
                        Log.e(TAG, "run: 洗澡步骤一="+num );
                        Thread.sleep(num);
                        sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXWATERCLOSE);
                        Thread.sleep(100);
                        sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXWATERPUMPCLOSE);
                        Thread.sleep(stepInterval);

                        sendFlowNum(4);
                        //开始喷沐浴露
                        stage=4;
                        num=(long)(bodyWashInt*totalMul);
                        setWashDown(num+stepInterval,stepTv,2);
                        setFlowMsg("洗狗中(沐浴露清洗)",num+stepInterval);
                        Thread.sleep(100);
                        sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXWATEROPEN);  //开水阀
                        Thread.sleep(100);
                        // 沐浴露在未满10秒钟的时候，按照流程时间喷。满10秒钟以上，先喷10秒钟沐浴露，其他时间喷水。护毛素也一样
                        if (num>bodyWashInt1){
                            sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXWASHOPEN);   //开沐浴露阀门
                            Thread.sleep(100);
                            sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXCONCENTRATEDOPEN);   //开浓缩液阀门
                            Thread.sleep(100);
                            sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXWATERPUMPOPEN);  //开高压泵阀门
                            Log.e(TAG, "run: 洗澡步骤二，沐浴露时间="+bodyWashInt1 );
                            Thread.sleep(bodyWashInt1);
                            sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXWASHCLOSE);  //关沐浴露门
                            Thread.sleep(100);
                            sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXCONCENTRATEDCLOSE);  //关浓缩液门
//                            Thread.sleep(100);
//                            sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXWATERPUMPCLOSE);     //关高压水泵
                            long num1=num-bodyWashInt1;
                            Log.e(TAG, "run: 洗澡步骤二，喷水时间="+bodyWashInt1 );
                            Thread.sleep(num1);
                        }else{
                            sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXWASHOPEN);   //开沐浴露阀门
                            Thread.sleep(100);
                            sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXCONCENTRATEDOPEN);   //开浓缩液阀门
                            Thread.sleep(100);
                            sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXWATERPUMPOPEN);  //开高压泵阀门
                            Log.e(TAG, "run: 洗澡步骤二="+num );
                            Thread.sleep(num);
                            sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXWASHCLOSE);  //关沐浴露门
                            Thread.sleep(100);
                            sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXCONCENTRATEDCLOSE);  //关浓缩液门
                            Thread.sleep(100);
                        }
                        sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXWATERPUMPCLOSE);     //关高压水泵
                        Thread.sleep(100);
                        sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXWATERCLOSE);     //关水阀
                        Thread.sleep(stepInterval);
                        sendFlowNum(5);
                        //开始第二次喷水清洗
                        stage=5;
                        num=(long) (twoWaterInt*totalMul);
                        setWashDown(num+stepInterval,stepTv,3);
                        setFlowMsg("洗狗中(第二次清水冲洗)",num+stepInterval);
                        Thread.sleep(100);
                        sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXWATEROPEN);  //开水阀
                        Thread.sleep(100);
                        sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXWATERPUMPOPEN);  //开高压水泵
                        Log.e(TAG, "run: 洗澡步骤三="+num );
                        Thread.sleep(num);
                        sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXWATERCLOSE);
                        Thread.sleep(100);
                        sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXWATERPUMPCLOSE);
                        Thread.sleep(stepInterval);
                        sendFlowNum(6);
                        //开始喷护毛素
                        stage=6;
                        num=(long) (conditionerInt*totalMul);
                        setWashDown(num+stepInterval,stepTv,4);
                        setFlowMsg("洗狗中(护毛素冲洗)",num+stepInterval);
                        Thread.sleep(100);
                        sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXWATEROPEN);  //开水阀
                        Thread.sleep(100);
                        // 护毛素流程时间在未大过护毛素喷洒的时候，按照流程时间喷。如果大于护毛素喷洒时间，则护毛素喷洒时间为它本身的，剩余喷水时间为护毛素流程时间-护毛素喷洒时间
                        if (num>conditionerInt1){
                            sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXCONDITIONEROPEN);   //开护毛素阀门
                            Thread.sleep(100);
                            sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXCONCENTRATEDOPEN);   //开浓缩液阀门
                            Thread.sleep(100);
                            sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXWATERPUMPOPEN);  //开高压泵阀门
                            Log.e(TAG, "run: 洗澡步骤四，护毛素时间="+conditionerInt1 );
                            Thread.sleep(conditionerInt1);
                            sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXCONDITIONERCLOSE);
                            Thread.sleep(100);
                            sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXCONCENTRATEDCLOSE);  //关浓缩液阀门
                            long num1=num-conditionerInt1;
                            Log.e(TAG, "run: 洗澡步骤四,喷水时间="+num1 );
                            Thread.sleep(num1);
                        }else{
                            sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXCONDITIONEROPEN);   //开护毛素阀门
                            Thread.sleep(100);
                            sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXCONCENTRATEDOPEN);   //开浓缩液阀门
                            Thread.sleep(100);
                            sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXWATERPUMPOPEN);  //开高压泵阀门
                            Log.e(TAG, "run: 洗澡步骤四，护毛素时间="+num );
                            Thread.sleep(num);
                            sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXCONDITIONERCLOSE);
                            Thread.sleep(100);
                            sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXCONCENTRATEDCLOSE);  //关浓缩液阀门
                            Thread.sleep(100);
//                            sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXWATERPUMPCLOSE);
//                            Thread.sleep(100);
                        }
                        sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXWATERPUMPCLOSE);  //关闭高压水泵
                        Thread.sleep(100);
                        sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXWATERCLOSE);     //关水阀
                        Thread.sleep(stepInterval);

                        sendFlowNum(7);
                        //开始第三次喷水清洗
                        stage=7;
                        num=(long) (threeWaterInt*totalMul);
                        setWashDown(num+stepInterval,stepTv,5);
                        setFlowMsg("洗狗中(第三次清水冲洗)",num+stepInterval);
                        Thread.sleep(100);
                        sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXWATEROPEN);  //开水阀
                        Thread.sleep(100);
                        sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXWATERPUMPOPEN);  //开高压水泵
                        Log.e(TAG, "run: 洗澡步骤五="+num );
                        Thread.sleep(num);
                        sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXWATERCLOSE);
                        Thread.sleep(100);
                        sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXWATERPUMPCLOSE);

                    }
                    Thread.sleep(stepInterval);
                    sendFlowNum(8);
                    Log.e("TAG", "run: 洗狗机洗澡完成" );
                    Log.e("TAG", "run: 洗狗机烘干开始" );
                    //烘干功能
                    /**烘干功能开启（时间）*/
                    stage=8;
                    long num1=(long) (dryInt*totalMul);
                    long num=(long) (num1+preheatInt);
                    setWashDown(num+10,stepTv,6);
                    setFlowMsg("洗狗中(烘干毛发)",num+10000);
                    Thread.sleep(100);
                    sendMechineOrders(SerialConfigUtil.SendHex25);
                    Thread.sleep(100);
//                    sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXHEATINGOPEN);  //加热条打开
//                    setPreHeat();//如果是根据室温来打开加热丝，则不需要隔段时间进行加热这个功能
                    Thread.sleep(preheatInt);
                    sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXHAIRDRYEROPEN);//吹风机开
                    Log.e(TAG, "run: 洗澡步骤六="+num );
                    Thread.sleep(num1);
//                    if (heatThread!=null){
//                        isHeatClose=false;
//                        heatThread.interrupt();
//                    }
//                    Thread.sleep(100);
                    sendMechineOrders(SerialConfigUtil.SendHex26);
                    Thread.sleep(100);
                    sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXHAIRDRYERCLOSE);//关闭吹风机
//                    Thread.sleep(100);
//                    sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXHEATINGCLOSE);//关闭加热条
                    Log.e("TAG", "run: 洗狗机烘干结束" );
//                    speakOut("您的爱宠已经洗好了，请开门带它离开");
                    sendFlowNum(9);
                    //洗完开门
                    Thread.sleep(100);
                    sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXOPENDOOR1);
                    if (flowFragment!=null){
                        flowFragment.clearFlick(8);
                    }
                    setFlowMsg("已洗完，取宠中，下阶段是消毒",0);
                }catch (InterruptedException e) {
                    Log.e(TAG,"洗狗机线程休眠被中断，程序退出。");
                    Thread.currentThread().interrupt();
                    if (flowFragment!=null){
                        flowFragment.clearFlick(stage);
                    }
                    stopDogWash();
                }

            }
        });
        dryThread.start();
    }

    private void setFlowMsg(String flowMsg,long progressTime){
        FlowMsgBean flowMsgBean=new FlowMsgBean();
        flowMsgBean.setSn(FlyUtil.getSn(DogActivity.this));
        flowMsgBean.setProcessName(flowMsg);
        if (progressTime!=0){
            flowMsgBean.setProcessTime(""+(progressTime/1000));
        }
        flowMsgBean.setRoomTemp(""+houseTem1);
        flowMsgBean.setWaterTemp(""+waterTem1);
        String time=DateUtil.now();
        flowMsgBean.setUpTime(time);
        if(mSocketService!=null){
            mSocketService.publishDogFlow(flowMsgBean);
        }
    }

    private boolean isHeatClose=true;
    Thread heatThread=null;


    private void setPreHeat(){
        heatThread=new Thread(new Runnable() {
            @Override
            public void run() {
                while (isHeatClose){
                    try {
                        sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXHEATINGOPEN);  //加热条打开
                        Log.e(TAG, "run: 步骤继续加热条开" );
                        Thread.sleep(preheatInt1);
                        sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXHEATINGCLOSE);//关闭加热条
                        Log.e(TAG, "run: 步骤继续加热条---关闭" );
                        Thread.sleep(preheatInt2);
                    }catch (Exception e){
                        e.printStackTrace();
                        Thread.currentThread().interrupt();
                    }

                }
                //如果结束后，需要将值重新归回默认
                isHeatClose=true;
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXHEATINGCLOSE);

            }
        });
        heatThread.start();
    }

    CountDownTimer countDownTimer;
    private void setWashDown(long num,TextView textView,int step){
        Message message=handler.obtainMessage();
        message.what=DOGFLOWTIME;
        message.obj=num;
        message.arg1=step;
        handler.sendMessage(message);
    }

    private synchronized void setWashDetail(long num,int step){
        if (countDownTimer!=null){
            countDownTimer.cancel();
        }
        countDownTimer=new CountDownTimer(num*1000,1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                flowLeaveTime= (int) (millisUntilFinished);
//                Log.e(TAG, "onTick: 当前设备状态还有多少时间="+flowLeaveTime );
                if (stepTv!=null){
                    if (step==6){
                        stepTv.setText("还剩下"+Math.ceil(millisUntilFinished/1000/60.0)+"分钟洗完澡");
                    }else{
                        if (step==1){
                            flowDogLeaveTime=(int)((totalMul*(bodyWashInt+twoWaterInt+conditionerInt+threeWaterInt+dryInt))+millisUntilFinished);
                        }else if (step==2){
                            flowDogLeaveTime=(int)((totalMul*(twoWaterInt+conditionerInt+threeWaterInt+dryInt))+millisUntilFinished);
                        }else if (step==3){
                            flowDogLeaveTime=(int)((totalMul*(conditionerInt+threeWaterInt+dryInt))+millisUntilFinished);
                        }else if (step==4){
                            flowDogLeaveTime=(int)((totalMul*(threeWaterInt+dryInt))+millisUntilFinished);
                        }else if (step==5){
                            flowDogLeaveTime=(int)((totalMul*(dryInt))+millisUntilFinished);
                        }

//                        Log.e(TAG, "onTick: 当前步骤的时间="+(millisUntilFinished/1000)+",总体洗完还需"+(flowDogLeaveTime/1000) );
//                        Log.e(TAG, "onTick: 在当前步骤还剩下"+Math.ceil(millisUntilFinished/1000/60.0)+"分钟,总体洗完还需"+Math.ceil(flowDogLeaveTime/1000/60.0)+"分钟" );
                        int currentTime= (int) Math.ceil(millisUntilFinished/1000/60.0);
                        int totalTime= (int) Math.ceil(flowDogLeaveTime/1000/60.0);
                        stepTv.setText("在当前步骤还剩下 "+currentTime+" 分钟,总体洗完还需 "+totalTime+" 分钟");
                    }

                }
            }

            @Override
            public void onFinish() {

            }
        };
        countDownTimer.start();
    }

    /**
     * 消毒线程
     */
    private synchronized void startToDisinfection(){
        disinfectionThread=new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    stage=11;
                    setFlowMsg("消毒中(喷洒消毒液)",disinfectantInt);
                    Log.e(TAG, "run: 消毒工作开始" );
                    sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXWATEROPEN);  //开水阀
                    Thread.sleep(100);
                    sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXDISINFECTANTOPEN);   //开消毒液
                    Thread.sleep(100);
                    sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXCONCENTRATEDOPEN);   //开浓缩液阀门
                    Thread.sleep(100);
                    sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXWATERPUMPOPEN);  //开高压水泵
                    Log.e(TAG, "run: 洗澡步骤七="+disinfectantInt );
                    Thread.sleep(disinfectantInt);
                    sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXDISINFECTANTCLOSE);//关消毒液
                    Thread.sleep(100);
                    sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXCONCENTRATEDCLOSE);  //关浓缩液阀门
                    Thread.sleep(100);
                    sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXWATERPUMPCLOSE);  //关高压水泵
                    Thread.sleep(100);
                    sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXWATERCLOSE);     //关水阀

                    Log.e(TAG, "run: 往洗狗机里面吹风" );
                    stage=12;
                    setFlowMsg("消毒中(给洗狗机换风)",windChangeInt+stepInterval);
                    Thread.sleep(stepInterval);
                    sendMechineOrders(SerialConfigUtil.SendHex25);
                    Log.e(TAG, "run: 洗澡步骤八="+windChangeInt );
                    Thread.sleep(windChangeInt);
                    sendMechineOrders(SerialConfigUtil.SendHex26);

                    Log.e(TAG, "run: 再使用水冲洗一次" );
                    stage=13;
                    setFlowMsg("消毒中(最后一次清水冲洗)",fourWaterInt+stepInterval);
                    Thread.sleep(stepInterval);
                    sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXWATEROPEN);
                    Thread.sleep(100);
                    sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXWATERPUMPOPEN);  //开高压水泵
                    Log.e(TAG, "run: 洗澡步骤九="+fourWaterInt );
                    Thread.sleep(fourWaterInt);
                    sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXWATERCLOSE);
                    Thread.sleep(100);
                    sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXWATERPUMPCLOSE);
                    speakDogStateWarn("消毒工作已经完成，设备可以放心使用！");
                    Log.e(TAG, "run: 整个流程完成");
                    sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXLIGHTCLOSE);//关闭内照明
                    handler.sendEmptyMessage(DISINFECTANTSDISMISS);
                    stage=14;//到这里表明整个流程已经完成
                    setFlowMsg("空闲",0);
                }catch (InterruptedException e){
                    Log.e(TAG, "run: 消毒流程出现了异常");
                    Thread.currentThread().interrupt();
                    stopDogDisinfectant();
                }
            }
        });
        disinfectionThread.start();
    }


    private void startListenNet(){
        NetWorker=new Thread(new Runnable() {
            @RequiresApi(api = Build.VERSION_CODES.Q)
            @Override
            public void run() {
                while (!Thread.interrupted()) {
                    while (!cacheLinkedDeque2.isEmpty()) {
                        String msg = cacheLinkedDeque2.poll();
                        try {
                            handlerNetWork(msg);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    //Waiting for next file
                    synchronized (netObject) {
                        try {
                            //isEmpty() may take some time,so we set timeout to detect next file
                            netObject.wait(200);
                        } catch (InterruptedException e) {
//                        e.printStackTrace();
                            NetWorker.interrupt();
                        }
                    }

                }


            }
        });
        NetWorker.start();
    }

    private void startDogWork(){
        dogWorker=new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(10*1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                while (isDestroy){

                    if (mechineInt < 0) {
                        if (locationFlag) {
                            mechineInt = 10;

//                        2023.9.8  一定要添加isGaode，不然太多无网太多问题了
                            Log.e(TAG, "run: 经纬度定位开始="+sLanguage+";locationMode="+locationMode );
                            boolean isGaode=false;
                            if ("zh".equals(sLanguage) && locationMode){
                                if (isOnNet){       //高德地图需要有网络才执行  并且是4G网络的时候
                                    if (netdo!=30){       // 如果不是4G网络，则直接跳回GPS定位
                                        locationMode=false;
                                    }
                                    isGaode=true;
                                }
                            }else{
                                //直接使用GPS定位
                                isGaode=true;
                            }
                            if(isGaode){
                                locationFlag=false;
                                //这里表示只运行一次
                                if (gpsFlag) {
                                    gpsFlag = false;
                                    getLocation();
                                }
                            }


                        }

                    } else {
                        mechineInt--;
//                    Log.i(TAG, "run: 开机进行屏幕设置次数111="+mechineInt);
                    }

                    if (heatFlag){
                        if (heatInt<0){
                            //如果当前温度和开始拿到的温度一样或者差不多，则说明这个温度传感器是有问题的。上报异常，并且停止加热
                            //如果加热10分钟都没有往上升2°，则表明温度传感器出现了问题
                            if (waterTem-heatWaterTem>2){
                                //则表明温度传感器是正常的
                            }else{
                                //则表明温度传感器是有问题的，需要上报异常
                                exceType="101";
                                exceMark="温度传感器有问题";
                                //报异常
                                sendMechineExption("温度传感器有问题");
                                //取消加热
                                sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXWATERHEATINGCLOSE);
                            }
                            heatFlag=false;
                        }else{
                            heatInt--;
                        }
                    }

                    if (httpFlag){
                        if (httpInt<0){
                            httpInt=600;
                            //进行http的同步
                            Log.e(TAG, "run: 开始进行数据同步" );
                            handler.sendEmptyMessage(DOGSYNCCONFIG);

                        }else{
                            httpInt--;

//                            double temDle=FlyUtil.getOutTemp(DogActivity.this);
//                            DecimalFormat df=new DecimalFormat("#.0");
//                            String outTem=df.format(temDle);
//                            Log.e(TAG, "run: 室外温度为="+outTem);
                        }

                    }

                    if (dogConfigFlag){
                        if (dogConfigInt<0){
                            dogConfigInt=300;
                            getConfigData();
                        }else{
                            dogConfigInt--;
                        }

                    }


                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }

            }
        });
        dogWorker.start();

    }

    private void getConfigData(){
        DogConfigBean dogConfigBean=new DogConfigBean();
        dogConfigBean.setSn(FlyUtil.getSn(DogActivity.this));
        dogConfigBean.setUpTemp(houseUpper);
        dogConfigBean.setDownTemp(houseLower);
        dogConfigBean.setUpWaterTemp(upperWater);
        dogConfigBean.setDownWaterTemp(lowerWater);
        int ones=oneWaterInt/1000;
        dogConfigBean.setFirstWashTime(ones);
        int bodys=bodyWashInt/1000;
        dogConfigBean.setSoapTime(bodys);
        int bodys1=bodyWashInt1/1000;
        dogConfigBean.setSoapUseTime(bodys1);
        int twos=twoWaterInt/1000;
        dogConfigBean.setSecondWashTime(twos);
        int conditioners=conditionerInt/1000;
        dogConfigBean.setConditionerTime(conditioners);
        int conditioners1=conditionerInt1/1000;
        dogConfigBean.setConditionerUseTime(conditioners1);
        int threes=threeWaterInt/1000;
        dogConfigBean.setThirdWashTime(threes);
        int preheats=preheatInt/1000;
        dogConfigBean.setPreHotTime(preheats);
        int drys=dryInt/1000;
        dogConfigBean.setDryTime(drys);
        int disinfecttants=disinfectantInt/1000;
        dogConfigBean.setDisinfectTime(disinfecttants);
        int windChanges=windChangeInt/1000;
        dogConfigBean.setAirExchangeTime(windChanges);
        int fourWaters=fourWaterInt/1000;
        dogConfigBean.setFourthWashTime(fourWaters);
        int stepIntervals=stepInterval/1000;
        dogConfigBean.setStepTime(stepIntervals);
        dogConfigBean.setPhone(phoneNum);
        dogConfigBean.setQuickWashPrice(oneKeyWashPrice);
        dogConfigBean.setHighWashPrice(detailWashPrice);
        dogConfigBean.setSmallMultiple(smallDogPrice);
        dogConfigBean.setMiddleMultiple(midDogPrice);
        dogConfigBean.setLargeMultiple(bigDogPrice);
        dogConfigBean.setShortHairMultiple(shortHairPrice);
        dogConfigBean.setNormalMultiple(normalLongHairPrice);
        dogConfigBean.setLongHairMultiple(longHairPrice);
        dogConfigBean.setSparseMultiple(thinHairPrice);
        dogConfigBean.setThickNormalMultiple(normalHairPrice);
        dogConfigBean.setDenseMultiple(thickHairPrice);
        dogConfigBean.setDryMultiple(dryDogPrice);
        dogConfigBean.setDryWashMultiple(washDryPrice);
        String now= DateUtil.now();
        dogConfigBean.setUpTime(now);
        if(mSocketService!=null){
            mSocketService.publishDogConfig(dogConfigBean);
        }
    }

    private void getLocation() {
        if ("zh".equals(sLanguage) && locationMode) {
            Log.i(TAG, "run: 高德地图开始定位111");
            gaodeLocationUtils = new GaodeLocationUtils(new GaodeLocationUtils.ILocationListener() {
                @Override
                public void onSuccessLocation(AMapLocation location) {
                    if (gpsInt>0){
                        Log.i(TAG, "onSuccessLocation: 高德获取的GPS经纬度定位");
                        if(mSocketService!=null){
                            mSocketService.sendMechineGps(location.getLatitude(),location.getLongitude());
                        }
                        gpsInt--;
                    }else{
                        gaodeLocationUtils.cancelLocation();
                    }

                }
            });
            gaodeLocationUtils.location(DogActivity.this);

        } else {
            //海外则使用GPS定位
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    LocationUtils.addLocationListener(DogActivity.this, LocationManager.GPS_PROVIDER, new LocationUtils.ILocationListener() {
                        @Override
                        public void onSuccessLocation(Location location) {
                            if (gpsInt>0){
                                if (location != null) {
//                            ToastUtils.toast(ItfCameraActivity.this,"GPS位置，lat="+location.getLatitude()+";lng="+location.getLongitude());
                                    Log.i(TAG, "onSuccessLocation: GPS经纬度位置定位，lat=" + location.getLatitude() + ";lng=" + location.getLongitude());
                                    AMapLocation aMapLocation=fromGpsToAmap(location);
                                    if (mSocketService!=null){
                                        mSocketService.sendMechineGps(aMapLocation.getLatitude(),aMapLocation.getLongitude());
                                    }

                                } else {
//                            ToastUtils.toast(ItfCameraActivity.this,"GPS location 获取为空");
                                    Log.i(TAG, "onSuccessLocation: GPS location 获取为空");
                                }
                                gpsInt--;
                            }else{
                                LocationUtils.unRegisterListener(DogActivity.this);
                            }


                        }
                    });
                }
            });



        }
    }
    private AMapLocation fromGpsToAmap(Location location) {
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        latLng = GpsToGcj.transformFromWGSToGCJ(latLng);
        AMapLocation aMapLocation = new AMapLocation(location);
        aMapLocation.setLatitude(latLng.latitude);
        aMapLocation.setLongitude(latLng.longitude);
        return aMapLocation;
    }

    /**========================网络相关、网络类型相关=============================*/
    @RequiresApi(api = Build.VERSION_CODES.Q)
    private void handlerNetWork(String message) {
        if (message.length()>1){
            netType=Integer.valueOf(message.substring(1));
            message=message.substring(0,1);
        }
        switch (message){
            case "1":{
//                isGetOnNet();
                //4G信号处理
//                Log.i(TAG, "handlerNetWork: 4G网络获取到的dB="+isMobileEnableReflex(CombinActivity.this));
                if (PhoneUtil.isMobileEnableReflex(DogActivity.this)){
//
//                    //网络信号改变时，获取网络信息
//
                    String netWorkStatus = isFastMobileNetwork() ? "4" : "2";
                    int dbm=PhoneUtil.getMobileDbm(signal,mTelephonyManager);
                    Log.i(TAG, "当前为" + netWorkStatus + "，信号强度=" + dbm );
                    if (dbm!=-1){
                        if (mSocketService!=null){
                            mSocketService.signalValue(netWorkStatus+dbm);
//                            Log.i(TAG, "网络检查 当前是4G网络2222");
                        }
                    }
                }

                break;
            }
            case "2":{
//                isGetOnNet();
                if (manager==null){
                    break;
                }
                //wifi信号处理
                WifiInfo wifiInfo=manager.getConnectionInfo();
                String name=wifiInfo.getSSID();
                int rssi=wifiInfo.getRssi();
                if(mSocketService!=null){
                    mSocketService.signalValue("1"+rssi);
                }
                if (name==null){
                    name="unknow wifi";
                }
                String finalName=name;
                Log.i(TAG, "onReceive: wifi的信号强度为="+rssi);

                break;
            }
            case "3":{
                isNetWorkOnLine(netType);
                break;
            }
            case "4":{
                //无网络情况下，打开4G网络
                if (!mobileFlag){
                    Log.i(TAG, "onReceive: 开机网络 无网络情况下打开4G网络" );
//                            FlyUtil.initInot(CombinActivity.this).execSuCmd("svc data enable");
                    FlyUtil.open4G(DogActivity.this);
                    mobileFlag=true;
                }

                if(!currentApName.equals("inte")){
                    Log.i(TAG, "wifiap onReceive: 开机网络，无网络情况下，如果wifi开关不打开，则打开wifi开关" );
//                    WifiUtil.openwifi(WifiUtil.initWifiManager(CombinActivity.this));
                    if (WifiApMethodUtils.isWifiApEnabled(DogActivity.this)){
                        //如果有热点，先关闭热点
                        Log.i(TAG, "wifiap onReceive: 开机网络，无网络情况下，如果热点打开了，则先关闭热点" );
                        WifiApMethodUtils.closeWifiAP(DogActivity.this);
                        needOpenWifi=true;
                    }else{
                        //如果没有，则可以连接wifi
                        Log.i(TAG, "wifiap onReceive: 开机网络，无网络情况下，没有热点，则直接打开wifi" );
                        setWifi();
                    }

                }
                break;
            }
            case "5":{
                if (!manager.isWifiEnabled()){
                    Log.i(TAG, "wifi未打开，需要去打开 ");
                    FlyUtil.openWifi(DogActivity.this);
                    try {
                        Thread.sleep(10*1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Log.i(TAG, "wifi打开后，已经延时10秒钟 ");
                }
                //连接wifi网络
                String name=PreferenceUtil.getString(PreferenceUtil.WIFINAME, "");
                String pwd=PreferenceUtil.getString(PreferenceUtil.WIFIPW, "");
                int wifiType=PreferenceUtil.getInt(PreferenceUtil.WIFITYPE,2);
                if (name!=null && name.length()>0){
                    Log.i(TAG, "wifi打开后，开始连接wifi= "+name+";"+pwd);
                    boolean flag= WifiUtil.connectwifi(manager, name, pwd, wifiType);
                    if (!flag){
                        wifiConFlag=true;
                    }
                }

                break;
            }
            case "6":{
                if (!manager.isWifiEnabled()){
                    Log.i(TAG, "handlerNetWork:开机网络，wifi开关是关闭的吗 ");
                    FlyUtil.openWifi(DogActivity.this);
                }
                break;
            }
        }
    }

    private synchronized void setWifi(){
        if(isOnNet && netdo==10)return;
        if (wifiConFlag){
            Log.i(TAG, "setWifi: wifi进来了的标志");
            wifiConFlag=false;
            cacheLinkedDeque2.add("5");
            synchronized (netObject) {
                netObject.notifyAll();
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private synchronized void isNetWorkOnLine(int type){
        //先判断是否有网络，如果有网络，那么就取它的IP，打开它的softap；
        // 如果没有网络，记录它当前的ip那么将它down并且up一下，如果多次都是，则不再down和up;
        //
        boolean httpFlag= HttpUtil.ping();
        Log.i(TAG, "isNetWorkOnLine: 开机网络，信号类型为="+type+"；网络在线="+httpFlag);
        if (httpFlag){

//            isGetOnNet();

//            //开机进行一次自动重启设置
//            if (firstGetNetWorkFlag && isOpenRebootFlag){
//                firstGetNetWorkFlag=false;
//                t.setToNow();
//                Log.i(TAG, "isNetWorkOnLine: 开始定时时间="+t.hour);
//                AlarmUtil.rebootMechine(DogActivity.this,LampConfig.rebootTime);
//
//
//                //进行七牛云房间创建
//                if (cameraFragment != null)
//                    cameraFragment.createQiniuRoom();
//
//
//            }
            /**==============在这里进行token获取==================*/
            if (token==null){
                handler.sendEmptyMessage(DOGTOKEN);
            }


            //设置网络为ok
            if (cameraFragment != null) {
                cameraFragment.setNetworkFlag(true);
            }

            //获取功能码
//            if (function.length() == 0) {
//                //如果function值的长度为0，则说明这个是需要获取一次
//                getMechineData();
//            }

            //进行apk下载
            //如果pversion不等于null，说明没有下载完成。重启需要重新发送指令。主要是
            if (pversion != null) {

                getVerParams().clear();
                verParams=VersionUtil.startToUpdate(pversion,DogActivity.this);
                if (verParams!=null){
                    handler.sendEmptyMessage(VERSIONKEY);
                }
            } else if(lBoardVersion!=null){
                getVerParams().clear();
                verParams=VersionUtil.startToUpdate(lBoardVersion,DogActivity.this,Build.MODEL);
                if (verParams!=null){
                    handler.sendEmptyMessage(VERSIONKEY);
                }
            } else if (isCheckFlag) {
                Log.i(TAG, "开机:查询版本，每次程序跑只会开启一次 ");
                isCheckFlag = false;
                verParams=VersionUtil.startToCheck(DogActivity.this); //这个如果没有上面那个pversion，这个每次开启只会检查一次
                if (verParams!=null){
                    isCallBoardVersion=true;
                    handler.sendEmptyMessage(VERSION);
                }else{
                    getVerParams().clear();
                    verParams= VersionUtil.startToCheck(DogActivity.this,Build.MODEL); //检查固件的更新
                    if (verParams!=null){
                        isCallBoardVersion=false;
                        handler.sendEmptyMessage(VERSION);
                    }
                }

            }


//            isDownLoadFirst = true;

            isOnNet=true;
            String ipStr="";
            //获取IP
            if (type==1){
                netInt=1;
                lastNet=1;
                if(mSocketService!=null){
                    mSocketService.signalValue("line");
                }
                phoneIp= IPUtil.getIpAddress("eth1");

                try {
                    FlyUtil.lanSoftAp(DogActivity.this,1);
                }catch (Exception e){
                    e.printStackTrace();
                }
                if (locationFlag){
                    wifiApDo();//在这里进行一次热点开启
                }
            }else if (type==2){
                lastNet=2;
                netInt=2;

                phoneIp=IPUtil.getIpAddress("wlan0");
                wlan0Ip=phoneIp.substring(0,phoneIp.lastIndexOf("."));
                Log.i(TAG, "isNetWorkOnLine: 开机网络 当前获取的wlan口ip为="+wlan0Ip);
                try {
                    Thread.sleep(2000);
                    FlyUtil.lanSoftAp(DogActivity.this,2);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }else if (type==3){
                lastNet=3;
                netInt=3;

                phoneIp=IPUtil.getIpAddress("wwan0");
                try {
                    FlyUtil.lanSoftAp(DogActivity.this,3);
                }catch (Exception e){
                    e.printStackTrace();
                }
                if (locationFlag){
                    wifiApDo();//在这里进行一次热点开启
                }
            }
            Log.i(TAG, "isNetWorkOnLine: 开机IP地址="+phoneIp );
            if (mSocketService!=null){
                mSocketService.sendIpAndVersion(phoneIp,mechineModel,appVersion,FlyUtil.initInot(this).getSystemVersion());
            }

            //可以开始进行初始化判断了
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }else{
            isOnNet=false;
            Log.i(TAG, "run: 开机网络====无网络");
            try {
                if (type==1){
                    //如果上一次网络不是有线网络，那么这次网络显示IP地址但是又没有网络的时候，会让网线down和up一下，以免出现内部eth1口和交换机口没断开。导致有假网络的情况
                    if (lastNet==1){
//                                FlyUtil.initInot(CombinActivity.this).execSuCmd("ifconfig eth1 down");
                        //如果当前有ap热点开着，先关闭ap热点
                        boolean apOpenFlag=WifiApMethodUtils.isWifiApOpen(manager);
                        if (apOpenFlag){
                            WifiApMethodUtils.closeWifiAP(DogActivity.this);
                        }
                        FlyUtil.closeEth1(DogActivity.this);
                        Thread.sleep(1000);
//                                FlyUtil.initInot(CombinActivity.this).execSuCmd("ifconfig eth1 up");
                        FlyUtil.openEth1(DogActivity.this);
                        lastNet=100;
                    }
                }else if (type==2){

                }else if (type==3){

                }
            }  catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        networkworkingFlag=true;

    }

    int NET_ETHERNET = 1;
    int NET_WIFI = 2;
    int NET_4G = 3;
    int NET_NOCONNECT = 0;
    private int isNetworkAvailable(Context context){
        if (connectivityManager!=null)
            connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

//        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkCapabilities networkCapabilities = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            networkCapabilities = connectivityManager.getNetworkCapabilities(connectivityManager.getActiveNetwork());
            if (networkCapabilities == null) {
                Log.i(TAG, "当前没有网络，请打开网络");
                return NET_NOCONNECT;
            } else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
                Log.i(TAG, "当前使用移动网络");
                return NET_4G;
            } else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
                Log.i(TAG, "当前使用WIFI网络");
                return NET_WIFI;
            }else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)){
                Log.i(TAG, "当前使用网线网络");
                return NET_ETHERNET;
            }else{
                return NET_NOCONNECT;
            }
        }else{
            NetworkInfo ethNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_ETHERNET);
            NetworkInfo wifiNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

            NetworkInfo networkInfo=connectivityManager.getActiveNetworkInfo();
            if (networkInfo!=null && networkInfo.isConnected()){

                if (networkInfo.getType()==ConnectivityManager.TYPE_MOBILE){
                    Log.i(TAG, "isNetworkAvailable: 连接4G" );
                    return NET_4G;
                }else if (networkInfo.getType()==ConnectivityManager.TYPE_WIFI){
                    Log.i(TAG, "isNetworkAvailable: 连接wifi" );
                    return NET_WIFI;
                }
//            Log.i(TAG, "isNetworkAvailable: 有网络" );

            }
            if (ethNetInfo != null && ethNetInfo.isConnected()) {
                return NET_ETHERNET;
            } else if (wifiNetInfo != null && wifiNetInfo.isConnected()) {
                return NET_WIFI;
            }  else{
                return NET_NOCONNECT;
            }
        }
    }

    /**
     * 判断网络连接
     * @return
     */
    private void isConnectIsNormal() {
        if (connectivityManager != null)
            connectivityManager = (ConnectivityManager) this.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connectivityManager.getActiveNetworkInfo();
//        Log.i(TAG, "isConnectIsNormal: wifi状态 检查当前网络状态" );
//        if (info!=null && info.isAvailable()){
        if (info != null && info.isAvailable() && !"Ethernet".equals(info.getTypeName())) {
            String name = info.getTypeName();
            Log.i("tiwolf", "wifi状态 当前网络名称："+name);
            Log.i("tiwolf", "wifi状态 当前网络名称："+info.isConnected());
            Log.i("tiwolf", "wifi状态 当前网络名称："+info.getExtraInfo());
            Log.i("tiwolf", "wifi状态 当前网络名称："+info.describeContents());
            Log.i("tiwolf", "wifi状态 当前网络名称："+info.getDetailedState());
        } else {
            //打开wifi
//            Log.i("tiwolf", "wifi状态 没有可用网络" );

            connectWifiOr4G();
        }

    }

    //wifiswitch是指令wifi的开关，wififlag是wifi直连的标志
    private void connectWifiOr4G() {
        if (!PhoneUtil.hasSimCard(DogActivity.this) || PreferenceUtil.getBoolean(PreferenceUtil.WIFISWITCH, false) || PreferenceUtil.getBoolean(PreferenceUtil.WIFIFLAG, false)) {
            PreferenceUtil.commitBoolean(PreferenceUtil.WIFIFLAG, false);
            Log.i("tiwolf", "initData: wifi状态如果没有sim卡");
            if (wifiConFlag){
                wifiConFlag=false;
                cacheLinkedDeque2.add("5");
                synchronized (netObject) {
                    netObject.notifyAll();
                }
            }
        }
    }

    /**
     * 判断网络速度
     */
    private boolean isFastMobileNetwork() {
        if (mTelephonyManager.getNetworkType() == TelephonyManager.NETWORK_TYPE_LTE) {
            //这里只简单区分两种类型网络，认为4G网络为快速，但最终还需要参考信号值
            return true;
        }
        return false;
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void wifiApDo() {
        if (manager==null)return;
        Log.i(TAG, "ap热点 wifiApDo: 开始");
        Boolean aBoolean = PreferenceUtil.getBoolean(PreferenceUtil.APSWITCH, false);
        Log.i(TAG, "1.ap热点 wifiApDo: 开始" + aBoolean);
        if (aBoolean) {
            //开启热点
            String apName1 = PreferenceUtil.getString(PreferenceUtil.APNAME, apName);
            String apPw = PreferenceUtil.getString(PreferenceUtil.APPW, apPwd);
            int apType1 = PreferenceUtil.getInt(PreferenceUtil.APTYPE, apType);
            Log.i(TAG, "ap热点 wifiApDo账号：" + apName1 + ";密码：" + apPw + ";类型：" + apType1);
            //是否是更改热点名称了,如果是更改名称了。
            if(currentApName.length()>0 && !currentApName.equals(apName1)){
                currentApName=apName1;
                WifiApMethodUtils.closeWifiAP(DogActivity.this);
                Log.i(TAG, "wifiApDo:ap热点更改名称了，关闭了热点之后再重新开启 ");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            currentApName=apName1;
            boolean apOpenFlag=WifiApMethodUtils.isWifiApOpen(manager);
            Log.e(TAG, "wifiApDo:热点是否打开= "+apOpenFlag );
            if (!apOpenFlag){
                WifiConfiguration wifiConfiguration=WifiApMethodUtils.createWifiInfo2(apName1,apPw,apType1);
                boolean flag=WifiApMethodUtils.setWifiApConfiguration(manager,wifiConfiguration);
                Log.i(TAG, "wifiApDo: 配置热点成功="+flag );
                WifiApMethodUtils.openWifiAP(DogActivity.this);
                Log.i(TAG, "ap热点第一次开启 ");
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //在这里先检查下是否有ip，如果没有再进行关闭打开动作
            String wlanIp=IPUtil.getIpAddress("wlan0");
            Log.i(TAG, "run: wlan0热点获取到的地址为="+wlanIp);
            if (wlanIp==null || wlanIp.contains(wlan0Ip)){
                WifiApMethodUtils.closeWifiAP(DogActivity.this);
                Log.i(TAG, "ap热点第一次关闭 ");
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (apOpenFlag){
                    //如果热点之前是打开的，那么关闭热点之后再进行名称和密码配置
                    WifiConfiguration wifiConfiguration=WifiApMethodUtils.createWifiInfo2(apName1,apPw,apType1);
                    boolean flag=WifiApMethodUtils.setWifiApConfiguration(manager,wifiConfiguration);
                }
                WifiApMethodUtils.openWifiAP(DogActivity.this);
                Log.i(TAG, "ap热点第二次开启 ");
            }


        } else {
            //关闭热点
//            WifiApMethodUtils.closeWifiAP(CombinActivity.this);
//            WifiApUtils.closeWifiApSwitch(manager);
            WifiApMethodUtils.closeWifiAP(DogActivity.this);
            Log.i(TAG, "wifiap热点第二次关闭 ");

        }
    }

    @Override
    public void backPayParam() {

    }

    private double totalMoney;
    private String dogTypeStr,hairLongStr,hairLessStr,washTypeStr;//爱犬类型，毛发类型，稀疏程度，洗宠类型
    @Override
    public void detailSubmit(double totalMul,double totalMoney,String dogTypeStr,String hairLongStr,String hairLessStr,String washTypeStr) {
        if (totalMul<=0){
            totalMul=1;
        }
        if (totalMoney<=0){
            totalMoney=0.01;
        }
        this.totalMul=totalMul;
        this.totalMoney=totalMoney;
        this.dogTypeStr=dogTypeStr;
        this.hairLongStr=hairLongStr;
        this.hairLessStr=hairLessStr;
        this.washTypeStr=washTypeStr;
        Log.e(TAG, "onClick: 高端精洗当前的倍数="+totalMul );
        dogWashType=DogWashType.DETAILWASH;
        handler.sendEmptyMessage(DOGPAYURL);

        showPayDialog();
    }

    class NetWorkBroadCastReciver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
//            long netStart=System.currentTimeMillis();
            String action = intent.getAction();
            Log.i(TAG, "开机网络显示返回活动标志onReceive: "+action );
            if (ConnectivityManager.CONNECTIVITY_ACTION.equals(action)){
                Log.i(TAG, "onReceive:开机获取的活动 ");
                switch (isNetworkAvailable(DogActivity.this)){
                    case 0:{
                        Log.i(TAG, "onReceive: 开机网络 无网络="+netInt );
//                        handler.sendEmptyMessage(CLOSERTMP);
                        if(cameraFragment!=null)
                            cameraFragment.stopRtmpStream();
                        isOnNet=false;

                        netInt=0;


                        cacheLinkedDeque2.add("4");
                        synchronized (netObject) {
                            netObject.notifyAll();
                        }

                        if(cameraFragment!=null){
                            cameraFragment.setNetworkFlag(false);
                        }


                        break;
                    }
                    case 1:{
                        Log.i(TAG, "onReceive: 开机网络 有线网络000="+netInt);
//                        inteflyApi.setMobileDataEnabled(false);
                        mobileFlag=false;
                        Log.i(TAG, "onReceive: 双网口的开机网络，关闭4G网络，看是否有4G通知" );

//                            Log.i(TAG, "onReceive: 开机网络 网线网络开启 ");
                        //设置一个中间值，来确保已经写到handler里面
                        if (netInt!=1){
//                            Log.i(TAG, "onReceive: 开机网络wifi网络222" );
                            if (networkworkingFlag){
                                networkworkingFlag=false;
                                cacheLinkedDeque2.add("31");
                                synchronized (netObject) {
                                    netObject.notifyAll();
                                }
                            }
                        }
                        netdo=10;



                        break;
                    }
                    case 2:{
                        Log.i(TAG, "onReceive: 开机网络wifi网络000="+netInt );

                        //设置一个中间值，来确保已经写到handler里面
                        if (netInt!=2){
                            Log.i(TAG, "onReceive: 开机网络wifi网络222" );
                            if (networkworkingFlag){
                                networkworkingFlag=false;
                                cacheLinkedDeque2.add("32");
                                synchronized (netObject) {
                                    netObject.notifyAll();
                                }
                            }
                            netdo=20;

                        }
                        wifiConFlag=true;
                        break;
                    }
                    case 3:{
                        Log.i(TAG, "onReceive: 开机网络 4G网络000="+netInt );
                        if(manager!=null && !manager.isWifiEnabled()){
                            Log.i(TAG, "onReceive: 开机网络，4G网络情况下，如果wifi开关不打开，则打开wifi开关" );
//                            WifiUtil.openwifi(WifiUtil.initWifiManager(CombinActivity.this));
                            FlyUtil.openWifi(DogActivity.this);
                        }

                        if (netInt!=3){
                            if (networkworkingFlag){
                                networkworkingFlag=false;
                                cacheLinkedDeque2.add("33");
                                synchronized (netObject) {
                                    netObject.notifyAll();
                                }
                            }
//                            netInt=30;
                            netdo=30;
                        }


                        break;
                    }
                    case 4:{
//                        getWeather(PreferenceUtil.getString(PreferenceUtil.GPSLATLNG,"22.65956,118.82299"));

                        break;
                    }
                    case 5:{

                    }
                }
            }else if(WifiManager.RSSI_CHANGED_ACTION.equals(action)){

                if (isOnNet && netdo==10)return;
                cacheLinkedDeque2.add("2");
                synchronized (netObject) {
                    netObject.notifyAll();
                }

                /**wifi 信号质量监听**/

            }else if ("android.net.wifi.WIFI_AP_STATE_CHANGED".equals(action)){
                int state = intent.getIntExtra("wifi_state",0);
                if(state==10){
                    Log.i(TAG, "onReceive: 开机网络 热点正在关闭");
                }else if (state==11){
                    Log.i(TAG, "onReceive: 开机网络 热点已关闭,如果当前需要打开wifi标志="+needOpenWifi+";是否是网线标志="+(isOnNet && netdo==10));
                    if(needOpenWifi && !(isOnNet && netdo==10)){
                        needOpenWifi=false;
                        cacheLinkedDeque2.add("6");
                        synchronized (netObject) {
                            netObject.notifyAll();
                        }
                    }

                }else if (state==12){
                    Log.i(TAG, "onReceive: 开机网络 热点正在打开");
                }else if(state==13){
                    Log.i(TAG, "onReceive: 开机网络 热点已打开");
                }
            }
//            //检测是否是主线程的方法
//            boolean isMain=Thread.currentThread() == Looper.getMainLooper().getThread();
//            String mainStr=isMain?"主线程":"非主线程";
//            Log.i(TAG, "onNetworkWeak: "+isMain+mainStr );
//            getNetWorkInfo();

        }

    }


    /**
     * ====================手机信号及网络专场  start=============================
     */
    private class PhoneStatListener extends PhoneStateListener {
        //获取信号强度

        @Override
        public void onSignalStrengthsChanged(SignalStrength signalStrength) {
            Log.i(TAG, "onSignalStrengthsChanged: 开机获取手机信号======"+signalStrength.toString() );
            if (netdo==30){
                signal = signalStrength;
                cacheLinkedDeque2.add("1");
                synchronized (netObject) {
                    netObject.notifyAll();
                }

            }



            super.onSignalStrengthsChanged(signalStrength);
        }

        @Override
        public void onSignalStrengthChanged(int asu) {
            super.onSignalStrengthChanged(asu);
        }
    }

    /**========================网络相关、网络类型---end=============================*/

    boolean isplayIn=false;//是否有播放时段（包括广告、直播）
    boolean isPlayWrong=false;

    /**
     * 这里是进行列表播放控制的
     */
    public void playMediaFile(){
        Log.i(TAG, "startPlay: 进来广告  --开始" + isplayIn);
        if (mPlayer == null) {
            mPlayer = new MediaPlayer();
            mPlayer.setOnCompletionListener(this);
            mPlayer.setOnVideoSizeChangedListener(this);
            mPlayer.setOnInfoListener(this);
            mPlayer.setOnErrorListener(this);
            mPlayer.setOnPreparedListener(this);
            mPlayer.setOnSeekCompleteListener(this);
        }
        Log.i(TAG, "startPlay: 进来广告1  --开始");
        if (playItems != null && isplayIn) {
            if (playItems.size()>=1){
                musicVolumn=playItems.get(0).getVolumn();
            }
            //说明当前有音视频列表
            if (playInt >= playItems.size()) {

                Log.i(TAG, "playMediaFile: " + playInt);
                playInt = 0;
            }
            isInAdvertisement = true;

            Log.i(TAG, "startPlay: 进行广告播放  --开始");
            isPlayWrong = false;
            startPlay();
        } else {
            Log.i(TAG, "startPlay: 进行广告播放  --错误" + isPlay);

            if (isPlay) {
                isPlay = false;
                try {
                    Message message1 = handler.obtainMessage();
                    message1.what = FREEADV;
                    handler.sendMessage(message1);
                    playItems = null;
                } catch (Exception e) {
                    e.printStackTrace();
                    isPlayWrong = true;
                    Log.i(TAG, "startPlayer: 播放出错55" + mPlayer);
                    Log.i(TAG, "startPlayer: 播放出错55" + e.getMessage());
                }

            }

            if (isPlayWrong) {
                Message message=handler.obtainMessage();
                message.obj=getResources().getString(R.string.flushlist);
                message.what=WARNSHOW;
                message.arg1=1;
                handler.sendMessage(message);
            } else {
                Message message=handler.obtainMessage();
                message.what=WARNSHOW;
                message.arg1=2;
                handler.sendMessage(message);
            }

        }
    }

    boolean playError = false;
    boolean playFail = true;
    int playFailInt = 0;

    /**
     * 这里是进行具体文件播放解决的
     */
    public synchronized void startPlay(){
        Log.i(TAG, "startPlay: 进入广告播放");
        cancelCountDown();
        playError = false;
        isInFreeAdFlag=false;
        if (mPlayer == null) {
            mPlayer = new MediaPlayer();
            mPlayer.setOnCompletionListener(DogActivity.this);
            mPlayer.setOnVideoSizeChangedListener(DogActivity.this);
            mPlayer.setOnInfoListener(DogActivity.this);
            mPlayer.setOnErrorListener(DogActivity.this);
            mPlayer.setOnPreparedListener(DogActivity.this);
            mPlayer.setOnSeekCompleteListener(DogActivity.this);
        }

        if (playItems == null || playItems.size() == 0) {
            Log.i(TAG, "startPlay: 播放条目为空");
            isInFreeAdFlag=true;
            mPlayer.start();

            Log.i(TAG, "startPlay1: " + playInt);
            return;
        } else if (playItems.size() == 1) {
            Log.i(TAG, "startPlay: 只有一个音视频");

            //只有一个音视频和图片的时候
            //当前为音视频
            if (playItems.get(0).getPlayType() == 1 || playItems.get(0).getPlayType() == 2) {
                Log.i(TAG, "startPlay: 只有一个音视频1");
//                File file=new File(TestConfig.downloadFilePath+playItems.get(0).getPlayName());
                File file = null;
                if (sdPath == null || sdPath.length() == 0) {
                    file = new File(TestConfig.downloadFilePath + playItems.get(0).getPlayName());
                } else {
                    file = new File(sdPath + "/solar/download/" + playItems.get(0).getPlayName());
                }

                Log.i(TAG, "startPlay音视频: 王工文件长度=" + playItems.get(0).getDownloadTotal());
                Log.i(TAG, "startPlay音视频: 当前已经下载的=" + file.length());

                if (!file.exists() || (file.exists() && file.length() == 0)) {

                    //去下载
                    if (isdownloadFlag) {
//                        Log.i(TAG, "2020-10-09 startPlay: 单个音频更新");
                        if (playItems.get(0).getDownloadMd5() != null) {
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    sqliteManager.updatePlayer("0", 1, playItems.get(0).getDownloadMd5());
                                }
                            }).start();
                            Log.i(TAG, "threadPoolUploadFile: 单个音视频文件==下载11");
                            qiniuDownloadFile(playItems.get(0).getDownloadMd5());

                        }
                    }
                    Message message = handler.obtainMessage();
                    message.what = FREEADV;
                    handler.sendMessage(message);
                    //如果文件不存在，则播放下一首
//                startPlay();
                    playError = true;
                } else {
//                    if (sqliteManager.canPlayOrNot(playItems.get(0).getDownloadMd5())){
                    if (("" + file.length()).equals(playItems.get(0).getDownloadTotal())) {

                        isNullFlag = true;
                        Log.i(TAG, "startPlay: 已经下载完成");
                        Message message = handler.obtainMessage();
                        message.obj=file.getAbsolutePath();
                        message.what = SINGLESONG;
                        handler.sendMessage(message);

                    } else {
                        //先判断当前是否正在下载
                        if (isdownloadFlag) {
                            //没有下载完，继续下载
                            sqliteManager.updatePlayer("" + file.length(), playItems.get(0).getDownloadMd5());
                            Log.i(TAG, "threadPoolUploadFile: 单个音视频文件==下载22");
                            qiniuDownloadFile(playItems.get(0).getDownloadMd5());

                            Log.i(TAG, "startPlay: 当前视音频没有下载完，先去下载音频" + playItems.get(0).getPlayName());
                        }
                        playError = true;
                        Message message = handler.obtainMessage();
                        message.what = FREEADV;
                        handler.sendMessage(message);
//                        runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                shwotv.setText("没有下载完，先去下载音频");
//                            }
//                        });

                    }

                }
            } else if (playItems.get(0).getPlayType() == 3) {
                String path;
                if (sdPath == null || sdPath.length() == 0) {
                    path = TestConfig.downloadFilePath + playItems.get(0).getPlayName();
                } else {
                    path = sdPath + "/solar/download/" + playItems.get(0).getPlayName();
                }
                Log.i(TAG, "startPlay: 图片" + path);
//            String path1=TestConfig.downloadFilePath+"a065c7cf71d71b1212a87651034e2628.jpg";
                File file = new File(path);
                Log.i(TAG, "startPlay: 图片长度" + file.length());

                if (!file.exists() || (file.exists() && file.length() == 0)) {
                    //如果文件不存在，则播放下一首
                    Log.i(TAG, "startPlay: 文件不存在");

                    //去下载
                    if (isdownloadFlag) {
//                        Log.i(TAG, "2020-10-09 startPlay: 单张图片更新");
                        if (playItems.get(0).getDownloadMd5() != null) {
                            sqliteManager.updatePlayer("0", 1, playItems.get(0).getDownloadMd5());
                            Log.i(TAG, "threadPoolUploadFile: 单张图片进行更新==下载33");
                            qiniuDownloadFile(playItems.get(0).getDownloadMd5());
                        }
                    }

                    Message message = handler.obtainMessage();
                    message.what = FREEADV;
                    handler.sendMessage(message);
//                startPlay();
                    playError = true;
                } else {
                    //            File file=new File(path);
                    Log.i(TAG, "startPlay: " + path);
                    int playTime = playItems.get(0).getPlayTime();
                    if (file != null && ("" + file.length()).equals(playItems.get(0).getDownloadTotal())) {
                        isNullFlag = true;
                        long starttime=System.currentTimeMillis();
//                        Bitmap bm= BitmapFactory.decodeFile(file.getPath());
                        Bitmap bm=null;
                        if (screenWidth!=0 && screenHeight!=0){
                            bm= BitmapUtils.decodeSampledBitmapFromFd(file.getPath(),screenWidth,screenHeight);
                        }else{
                            bm= BitmapUtils.decodeSampledBitmapFromFd(file.getPath(),720,1280);
                        }
                        Log.i(TAG, "startPlay: 从文件到图片所需时间为="+(System.currentTimeMillis()-starttime) +";fileurl="+file.getPath());

                        Message message = handler.obtainMessage();
                        message.what = SHOWPICTURE;
                        message.obj = bm;
                        message.arg1 = playTime;
                        message.arg2 = 0;
                        handler.sendMessage(message);
                    }else{
                        //去下载
                        if (isdownloadFlag) {
//                        Log.i(TAG, "2020-10-09 startPlay: 单张图片更新");
                            if (playItems.get(0).getDownloadMd5() != null) {
                                sqliteManager.updatePlayer("" + file.length(), 1, playItems.get(0).getDownloadMd5());
                                Log.i(TAG, "threadPoolUploadFile: 单个图片文件==下载33");
                                qiniuDownloadFile(playItems.get(0).getDownloadMd5());
                            }
                        }

                        Message message = handler.obtainMessage();
                        message.what = FREEADV;
                        handler.sendMessage(message);
                        playError = true;
                    }
                }

            }


        } else {
            //一个时段多个音视频，或者图片的时候
            Log.i(TAG, "startPlay: 多个播放 条目");
            if (playInt == -1) {
                Log.i(TAG, "startPlay2: " + playInt);
                playInt = 0;
//                return;
            }
            PlayItem playItem = playItems.get(playInt);
            if (playItems.size() > playInt && (playItem.getPlayType() == 1 || playItem.getPlayType() == 2)) {


                File file;
                if (sdPath == null || sdPath.length() == 0) {
                    file = new File(TestConfig.downloadFilePath + playItem.getPlayName());
                } else {
                    file = new File(sdPath + "/solar/download/" + playItem.getPlayName());
                }
                Log.i(TAG, "startPlay音视频: 王工文件长度=" + playItem.getDownloadTotal());
                Log.i(TAG, "startPlay音视频: " + file.getName() + ";文件长度=" + file.length());

//                File file=new File(TestConfig.downloadFilePath+playItems.get(playInt).getPlayName());
                if (!file.exists() || (file.exists() && file.length() == 0)) {


                    if (isdownloadFlag) {
//                        Log.i(TAG, "2020-10-09 startPlay: 多个音视频更新");
                        if (playItem.getDownloadMd5() != null) {
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    sqliteManager.updatePlayer("0", 1, playItem.getDownloadMd5());

                                }
                            }).start();
                            Log.i(TAG, "threadPoolUploadFile: 列表音视频文件==下载44");
                            qiniuDownloadFile(playItem.getDownloadMd5());
                        }
                    }
                    playError = true;
                } else {
                    Log.i(TAG, "startPlay: 音视频----" + playInt + ";已经下载好的大小：" + file.length());
                    if (("" + file.length()).equals(playItem.getDownloadTotal())) {
                        //已经下载完，可以播放
                        Log.i(TAG, "startPlay:大小 " + playItem.getDownloadTotal());
                        Log.i(TAG, "startPlay: 已经下载完路径=" + file.getAbsolutePath());
                        isNullFlag = true;


                        try {
                            Message message = handler.obtainMessage();
                            message.what = LISTSONG;
                            message.obj=file.getAbsolutePath();
                            message.arg1 = playInt;
                            handler.sendMessage(message);


                            Log.i(TAG, "startPlay: 音视频" + playInt);


                        } catch (Exception e) {
                            e.printStackTrace();
                            Log.i(TAG, "startPlayer: 播放出错33");
                            Log.i(TAG, "startPlayer: 播放出错33" + e.getLocalizedMessage());
                        }
                    } else {

                        int downNum=sqliteManager.AvDownloadFlag(playItem.getDownloadMd5());
                        Log.i(TAG, "startPlay: http 广告下载的状态为="+downNum );
                        //先判断当前下载的状态，如果是1的时候才进入继续下载。不然则使用过原先线程继续下载
                        if (isdownloadFlag) {
                            //先检查数据库里面是否有这个数据，如果没有则要删除数据


                            //没有下载完，继续下载
                            sqliteManager.updatePlayer("" + file.length(), playItem.getDownloadMd5());
                            Log.i(TAG, "startPlay: 当前视音频没有下载完，先去下载音频" + playItem.getPlayName());
                            qiniuDownloadFile(playItem.getDownloadMd5());
                        }
                        playError = true;


                    }

                }

            } else if (playItems.size() > playInt && playItem.getPlayType() == 3) {
                String path;
                if (sdPath == null || sdPath.length() == 0) {
                    path = TestConfig.downloadFilePath + playItem.getPlayName();
                } else {
                    path = sdPath + "/solar/download/" + playItem.getPlayName();
                }
                Log.i(TAG, "startPlay图片: " + path);

//                String path=TestConfig.downloadFilePath+playItems.get(playInt).getPlayName();
//            String path1=TestConfig.downloadFilePath+"a065c7cf71d71b1212a87651034e2628.jpg";
                File file = new File(path);
                Log.i(TAG, "startPlay: 图片长度" + file.length());

                if (!file.exists() || (file.exists() && file.length() == 0)) {
                    //如果文件不存在，则播放下一首
                    Log.i(TAG, "startPlay: 文件不存在;md5="+playItem.getDownloadMd5());

                    //去下载
                    if (isdownloadFlag) {
//                        Log.i(TAG, "2020-10-09 startPlay: 多张图片更新");
                        if (playItem.getDownloadMd5() != null) {
                            sqliteManager.updatePlayer("0", 1, playItem.getDownloadMd5());

                            Log.i(TAG, "threadPoolUploadFile: 列表里面图片文件==下载66");
                            qiniuDownloadFile(playItem.getDownloadMd5());
                        }
                    }

                    playError = true;
                } else {
                    Log.i(TAG, "startPlay: " + path);
                    int playTime = playItem.getPlayTime();
                    Log.i(TAG, "startPlay: 已经下载图片的长度为="+file.length());
                    Log.i(TAG, "startPlay: 实际图片的长度为="+playItem.getDownloadTotal());
                    if (file != null && ("" + file.length()).equals(playItem.getDownloadTotal())) {
                        isNullFlag = true;

                        long starttime=System.currentTimeMillis();
//                        Bitmap bm= BitmapFactory.decodeFile(file.getPath());
                        Bitmap bm=null;
                        if (screenWidth!=0 && screenHeight!=0){
                            bm= BitmapUtils.decodeSampledBitmapFromFd(file.getPath(),screenWidth,screenHeight);
                        }else{
                            bm= BitmapUtils.decodeSampledBitmapFromFd(file.getPath(),720,1280);
                        }
                        Log.i(TAG, "startPlay: 从文件到图片所需时间为="+(System.currentTimeMillis()-starttime)+";fileurl="+file.getPath() );

                        Message message = handler.obtainMessage();
                        message.what = SHOWPICTURE;
                        message.obj = bm;
                        message.arg1 = playTime;
                        message.arg2 = 1;
                        handler.sendMessage(message);
                    }else{
                        //去下载
                        if (isdownloadFlag) {
                            if (playItem.getDownloadMd5() != null) {
                                sqliteManager.updatePlayer(""+file.length(), 1, playItem.getDownloadMd5());
                                Log.i(TAG, "threadPoolUploadFile: 列表图片文件已有下载==下载66");
                                qiniuDownloadFile(playItem.getDownloadMd5());
                            }
                        }

                        playError = true;
                    }

                }


            } else if (playItems.size() > playInt && playItem.getPlayType() == 4) {
//                Log.i(TAG, "startPlay文字: "+TestConfig.downloadFilePath+playItems.get(playInt).getPlayName() );

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //文字显示

                        if (mPlayer != null && mPlayer.isPlaying()) {
                            mPlayer.pause();
                        }
                        int playTime = playItem.getPlayTime();
                        Log.i(TAG, "startPlay: playtime=" + playTime);
                        if (playTime <= 0) {
                            startCountDown(10);
                        } else {
                            startCountDown(playTime);
                        }
                    }
                });


            } else if (playItems.size() > playInt && playItem.getPlayType() == 5) {
//                Log.i(TAG, "startPlay文字转语音: "+TestConfig.downloadFilePath+playItems.get(playInt).getPlayName() );

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //文字转音频
                        if (mPlayer != null && mPlayer.isPlaying()) {
                            mPlayer.pause();
                        }
                        String content = playItem.getContent();

                    }
                });


            }

            playInt++;
            if (playItems != null && playInt == playItems.size()) {
//                Log.i(TAG, "2020-10-09 startPlay: 更新结束");
                playInt = 0;
                //todo 2020.10.12
                //如果列表有文件可以播放，那么继续可以使用startPlay()。如果没有,则直接跳闲时广告
                Log.i(TAG, "startPlay: 列表是否有可播放文件标志" + isNullFlag);
                if (isNullFlag) {
                    //有文件，则可以继续循环。没有则不循环
                } else {
                    //直接跳回闲时广告，再提示未下载完 直接让其使用handler
                    Message message = handler.obtainMessage();
                    message.what = FREEADV;
                    handler.sendMessage(message);
                    Log.i(TAG, "startPlay: 跳到handler之后还继续下去？");
                    playError = false;
                }

            }
            if (playError) {
                Log.i(TAG, "startPlay: 播放出错，重新设置播放11");
                startPlay();//好像只有出错的时候或者没有下载完成的时候才会跳到这里来
            }
        }

    }

    /**
     * 七牛云下载部分
     * @param md5
     */
    private void qiniuDownloadFile(String md5){
        //七牛云下载部分
        Log.i(TAG, "qiniuDownloadFile: 七牛云进行下载开始"+isdownloadFlag );
        if (!isdownloadFlag) {
            return;
        }
        isdownloadFlag=false;
        Message message1 = handler.obtainMessage();
        message1.what = DOWNLOADQINIU;
        message1.obj = md5;
        handler.sendMessage(message1);
    }

    private void startCountDown(int second) {
        if (countDownThread != null) {
            countDownThread.cancel();
        }
        countDownThread = new CountDownThread(second * 1000, 1000);
        countDownThread.setOnCountDownTimeListener(this);
        countDownThread.start();
    }

    private void cancelCountDown() {
        if (countDownThread != null)
            countDownThread.cancel();
    }

    @Override
    public void onViewError(Throwable throwable) {

    }

    @Override
    public void onSuccessDogState() {

    }

    @Override
    public void onFailDogState() {

    }

    @Override
    public void onSuccessMerge(UpLoadGetBean<UpLoadGetSubBean> msg, String imageCreate) {
        //如果合并成功，则下一个
        String[] strings=imageCreate.split(",");
        if (strings.length==2){
//            Date date = TimeUtil.StrToDateNone(strings[0]);
//            String str = TimeUtil.DateToStr(date);//将时间转成yyyy-MM-dd HH:mm:ss格式
//            Log.i(TAG, "complete: 记录七牛云时间=" + str);
//            //上传当前警报记录,开始上传文件记录
//            uploadPoliceRecord(str,strings[1]);
            Log.i(TAG, "onSuccessMerge:报警过后上传mp4文件记录进行绑定 ");
            Message message1 = handler.obtainMessage();
            message1.what = RECORDUPLOAD;
            message1.obj = imageCreate;
            handler.sendMessage(message1);
        }
    }

    @Override
    public void onErrorMerge(Throwable throwable, String md5) {
        Log.i(TAG, "onErrorMerge: 通知服务器文件合并出现问题="+md5);
        if (md5!=null && !sqliteManager.updateRecordCheck(md5)){
            contentValues.clear();
            contentValues.put("rccontent", md5);
            contentValues.put("updateType", 10);  //状态1是我司的状态，状态10 为给服务器添加文件合并失败记录失败
            contentValues.put("dotime", "" + System.currentTimeMillis());
            contentValues.put("updateMsg", md5);
            sqliteManager.addUpdateRecord(contentValues);
        }
    }

    @Override
    public void nonGetMessage(String error) {
        Log.i(TAG, "nonGetMessage: 上传文件出现问题");
    }

    @Override
    public void onSuccessGetKey(QiniuMsgBean msg) {
        successGetQiniuKey(msg);
    }

    private synchronized void successGetQiniuKey(QiniuMsgBean msg){
        try {
            //成功获取到七牛云的密钥,这样子才上传，不然不上传
//        Log.i(TAG, "onSuccessGetKey成功获取七牛云上传信息: "+msg.toString());
            if (isCurDoPolice) {
                isCurDoPolice = false;
                qiniuFlag=true;
                Log.i(TAG, "onSuccessGetKey: 报警记录上传开始");
                //报警信息上传
                String token = msg.getData().getToken();
                md5 = msg.getData().getMd5();
//            Log.i(TAG, "onSuccessGetKey: 七牛云开始上传===="+token+";;;;"+uploadItem );
                if (uploadItem != null) {
//                Log.i(TAG, "七牛云开始上传: token为="+msg.getData());
                    String filePath = uploadItem.getFilePath();
                    String imageCreate = uploadItem.getLastModifiedTime();
                    if (uploadParams==null){
                        uploadParams=new HashMap<>();
                    }
                    uploadParams.put("x:priFile", "true");
                    uploadParams.put("x:owner",FlyUtil.getSn(DogActivity.this));
                    uploadParams.put("x:fileMd5", filePath);
                    Log.i(TAG, "onSuccessGetKey: 报警记录上传开始");
                    if (uploadManager != null) {
                        uploadManager.put(filePath, null, token, this, new UploadOptions(uploadParams, "test-type", true, null, null));
                    }
                }
            } else {
                qiniuFlag=false;
                Log.i(TAG, "onSuccessGetKey: 普通记录上传00000000000"+uploadItem);
                String token = msg.getData().getToken();
                md5 = msg.getData().getMd5();
//            Log.i(TAG, "onSuccessGetKey: 七牛云开始上传===="+token+";;;;"+uploadItem );
                if (uploadItem != null) {
//                Log.i(TAG, "七牛云开始上传: token为="+msg.getData());
                    String filePath = uploadItem.getFilePath();
                    if (uploadParams==null){
                        uploadParams=new HashMap<>();
                    }
                    uploadParams.put("x:priFile", "true");
                    uploadParams.put("x:owner", FlyUtil.getSn(DogActivity.this));
                    uploadParams.put("x:fileMd5", filePath);

                    if (uploadManager != null) {
                        uploadManager.put(filePath, null, token, this, new UploadOptions(uploadParams, "test-type", true, null, null));
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            isNotUpload = true;
            Log.i(TAG, "onSuccessGetKey: 七牛云异常" + e.getLocalizedMessage());
        }
    }

    @Override
    public void onFailGetKey(Throwable throwable) {
        //没有获取到七牛云密钥，不处理信息
        Log.i(TAG, "onFailGetKey: 获取七牛云上传失败" + throwable.toString());
        isNotUpload = true;
    }

    @Override
    public void onSuccessGetDownloadUrl(KeyMsgBean msg) {
        //成功获取到七牛云的下载地址，可以去下载
        if (msg != null && msg.getData() != null) {
            Log.i(TAG, "onSuccessGetKey成功获取七牛云下载信息: " + msg.toString());
            String url = msg.getData();
            if (url!=null && url.length() > 4) {
                Log.i(TAG, "onSuccessGetKey成功获取七牛云下载信息: " + url);
                setUploadFile(url);
            } else {
                isdownloadFlag = true;
            }
        } else {
            isdownloadFlag = true;
            //data:null
            if (msg.getData() == null) {
                //如果服务端没有文件了，那么将会删掉这个md5下载项
                if (downParams != null) {
                    String downloadMd5 = (String) downParams.get(UploadConfig.md5);
                    if (sqliteManager != null) {
                        sqliteManager.deleteDownloadItem(downloadMd5);
                    }
                }
            }
        }
    }

    @Override
    public void onFailGetDownloadUrl(Throwable throwable) {
        Log.i(TAG, "onFailGetKey: 获取七牛云下载失败" + throwable.toString());
        isdownloadFlag = true;
    }

    @Override
    public void onSuccessPolice(KeyMsgBean msg, Map<String, String> police) {
        Log.i(TAG, "onSuccessPolice: " + msg.getCode());
//        isNotUpload = true;
        sqliteManager.deleteUpdateRecord(police.get("alarmTime"));
        // 做记录删除
        sqlInt = 58;//等60s左右刚好一个mp4视频录制完成，然后进行文件上传
        //继续进行记录上传
        getNextUploadRecordHistory();
    }

    @Override
    public void onSuccessUpdateMsg(KeyMsgBean msg, String content) {
        Log.i(TAG, "onSuccessUpdateMsg: 成功上传一条历史记录"+content);
        //马上检查upload_record表格，如果有数据则继续上传
        sqliteManager.deleteUpdateRecord(content);  //删除已经上传的记录
        getNextUploadRecordHistory();//获取下一条需要上传的记录
    }

    @Override
    public void onFailUpdateMsg(Throwable throwable, String content, String md5) {
        Log.i(TAG, "onFailUpdateMsg: 上传历史记录失败,日期=" + content + ";文件md5=" + md5);
        //查询数据库表里面是否有这个数据，没有则添加
        if (content != null && content.length() != 0 && !sqliteManager.updateRecordCheck(content)) {
//            ContentValues contentValues1=new ContentValues();
            contentValues.clear();
            contentValues.put("rccontent", content);
            contentValues.put("updateType", 8);  //状态1是我司的状态，状态8 为给服务器添加历史记录失败
            contentValues.put("dotime", "" + System.currentTimeMillis());
            contentValues.put("updateMsg", md5);
            sqliteManager.addUpdateRecord(contentValues);
            Log.i(TAG, "onFailUpdateMsg: 上报失败导致保存到历史列表里面" + content);
        }
    }

    @Override
    public void onSuccessDelMsg(KeyMsgBean msg, String content) {
        Log.i(TAG, "onSuccessDelMsg: 成功删除历史记录");
        //马上检查upload_record表格，如果有数据则继续上传
        sqliteManager.deleteUpdateRecord(content);  //删除已经上传的记录

        getNextUploadRecordHistory();
    }

    @Override
    public void onFailDelMsg(Throwable throwable, String content) {
        Log.i(TAG, "onFailDelMsg: 删除历史记录失败");
        //查询数据库表里面是否有这个数据，没有则添加
        if (content != null && content.length() != 0 && !sqliteManager.updateRecordCheck(content)) {
//            ContentValues contentValues1=new ContentValues();
            contentValues.clear();
            contentValues.put("rccontent", content);
            contentValues.put("updateType", 2);     //状态2为删除服务器记录
            contentValues.put("dotime", "" + System.currentTimeMillis());
            sqliteManager.addUpdateRecord(contentValues);
            Log.i(TAG, "receiveWork: 上报删除记录失败保存到历史列表里面");
        }
    }

    @Override
    public void upSendErrorSuccess(UpLoadGetBean<ErrorBean> keyMsgBean) {
        Log.i(TAG, "upSendErrorSuccess: 上传错误码数据成功=");
        if (keyMsgBean!=null && keyMsgBean.getData()!=null){
            int tfInt=keyMsgBean.getData().getTf();
            Log.i(TAG, "upSendErrorSuccess: 11上传错误码数据成功="+tfInt);
            if (keyMsgBean.getData().getTf()!=0){
                //为0表示为null
                int flag=keyMsgBean.getData().getTf();
                if(flag==-1){
                    //说明tfcard异常
                    tfcardErrorFlag=false;
                    PreferenceUtil.commitInt(PreferenceUtil.SDCARDERRORFLAG,1);
                }else if (flag==1){
                    //说明tfcard是正常的
                    tfcardErrorFlag=true;
                    PreferenceUtil.commitInt(PreferenceUtil.SDCARDERRORFLAG,0);
                }
                Log.i(TAG, "upSendErrorSuccess: 22上传错误码数据成功="+tfcardErrorFlag);
            }else if(keyMsgBean.getData().getCamera()!=0){
                //为0表示为null

            }else if(keyMsgBean.getData().getController()!=0){
                //为0表示为null

            }else if(keyMsgBean.getData().getLamppost()!=0){
                //为0表示为null

            }else if(keyMsgBean.getData().getNetwork()!=0){
                //为0表示为null

            }else if(keyMsgBean.getData().getScreen()!=0){
                //为0表示为null

            }else if(keyMsgBean.getData().getSpeaker()!=0){
                //为0表示为null

            }
        }
    }

    @Override
    public void upSendErrorFail(Throwable throwable) {
        Log.i(TAG, "upSendErrorSuccess: 上传错误码数据失败");
    }

    @Override
    public void onSuccessCheckKey(UpLoadGetBean<CheckMsgBean> msg) {
        //成功获取到检查信息

        /**
         * {"code":"0","data":{"pversion":"1.0.1","status":2,
         * "releaseTime":1590481665000,"updateContent":"1.修改内容不清楚",
         * "packageSize":695873522},"msg":null,"dataFlag":0}
         */
        Log.i(TAG, "onSuccessCheckKey: 有返回" );
        if (msg!=null){
            if (msg.getData()==null){
                //app版本没有获取到数据，那么就开始访问固件版本
                if (isCallBoardVersion){
                    Log.i(TAG, "onSuccessCheck: 当前app版本为最新版本，不需要做升级.删除对应文件");
                    FileSortUtil.delSubFile(FileSortUtil.appVer);

                    //需要call固件版本
                    isCallBoardVersion=false;
                    getVerParams().clear();
                    verParams= VersionUtil.startToCheck(DogActivity.this,Build.MODEL); //检查固件的更新
                    if (verParams!=null){
                        handler.sendEmptyMessage(VERSION);
                    }
                }else{
                    Log.i(TAG, "onSuccessCheck: 当前固件版本为最新版本，不需要做升级.删除对应文件");
                    FileSortUtil.delSubFile(FileSortUtil.boardVer);
                }
            }else{
                if (isCallBoardVersion){
                    isCallBoardVersion=false;
                    //app版本里面有东西
                    getVerParams().clear();
                    verParams=VersionUtil.afterSuccessGetVersionInfo(msg,pversion,DogActivity.this);
                    if (verParams!=null){
                        mPresenter.getUpdateKey(verParams);
                    }
                }else{
                    //固件版本里面有东西
                    getVerParams().clear();
                    verParams=VersionUtil.afterSuccessGetVersionInfo(msg,lBoardVersion,DogActivity.this,Build.MODEL);
                    if (verParams!=null){
                        mPresenter.getUpdateKey(verParams);
                    }
                }

            }

        }
    }

    @Override
    public void onSuccessKey(KeyMsgBean msg) {
        //获取到升级秘钥
        Log.i(TAG, "下载升级 onSuccessKey得到的秘钥为: " + msg.getData());
        if (msg.getData()==null)return;
        if (!PreferenceUtil.getBoolean(PreferenceUtil.PACKAGEFLAG, false)) {
            VersionUtil.doAfterGetKey(DogActivity.this,msg,sdPath,pversion,threadPoollExcutorUtil);
        }
    }

    @Override
    public void onSuccessPayUrl(UpLoadGetBean<PayBean> payMsg) {
        Log.e(TAG, "onSuccessPay: 获取到支付的url" );
        payUrl=payMsg.getData().getQrCode();
        urlBmp= ZxingUtil.createQRCodeBitmap(payUrl, 240, 240,"UTF-8","H", "1", Color.BLACK, Color.WHITE);
        Log.e(TAG, "onSuccessPayUrl: 获取到的url="+payUrl);
        orderNo=payMsg.getData().getOrderInfo().getOrderNo();
        Log.e(TAG, "onSuccessPayUrl: 获取到的订单号="+orderNo);
        amount=payMsg.getData().getOrderInfo().getAmount();
        Log.e(TAG, "onSuccessPayUrl: 所需的金额为="+amount);
        washType=payMsg.getData().getOrderInfo().getWashType();
        if (!"QUICKWASH".equals(washType)){
            // 说明是高端精洗
            doyType=payMsg.getData().getOrderInfo().getBodyFeature();
            Log.e(TAG, "onSuccessPayUrl: 获取到的狗大小="+doyType);
            hairType=payMsg.getData().getOrderInfo().getHairFeature();
            Log.e(TAG, "onSuccessPayUrl: 获取到的狗毛发长短="+hairType);
            hairthick=payMsg.getData().getOrderInfo().getTickFeature();
            Log.e(TAG, "onSuccessPayUrl: 获取到的狗毛发厚薄="+hairthick);
            washTp=payMsg.getData().getOrderInfo().getWashType();
            Log.e(TAG, "onSuccessPayUrl: 获取到的洗漱类型="+washTp);
            payContent=washType;
            if (washTp.equals("烘干")){
                dogBoxType=DogBoxType.DRY;
            }else{
                dogBoxType=DogBoxType.BADR;
            }
            handler.sendEmptyMessage(DOGPAYSHOW);
        }else{
            dogBoxType=DogBoxType.BADR;
            // 说明是一键洗狗
            handler.sendEmptyMessage(DOGPAYONESHOW);
        }
    }

    @Override
    public void onFailPay(Throwable throwable) {
        Log.e(TAG, "onSuccessPay: 支付失败后的信息="+throwable );
    }

    @Override
    public void onSuccessRefundPay(UpLoadGetBean<RefundBean> refundBean) {



    }

    @Override
    public void onFailRefundPay(Throwable throwable) {

    }

    @Override
    public void onSuccessUploadDogException(KeyMsgBean keyMsgBean) {

    }

    @Override
    public void onFailUploadDogException(Throwable throwable) {

    }

    @Override
    public void onSuccessGetToken(UpLoadGetBean<DogTonkenBean> dogTonkenBeanUpLoadGetBean) {

        if (dogTonkenBeanUpLoadGetBean!=null && dogTonkenBeanUpLoadGetBean.getData()!=null){
            token=dogTonkenBeanUpLoadGetBean.getData().getToken();
            Log.e(TAG, "onSuccessGetToken: 获取到的token为="+token );
            if (token!=null){
                PreferenceUtil.commitString(PreferenceUtil.DOGTOKEN,token);
            }
        }
    }

    @Override
    public void onFailGetToken(Throwable throwable) {
        Log.e(TAG, "onFailGetToken: token获取失败" );
    }

    @Override
    public void onSuccessUploadDogAlarm(KeyMsgBean keyMsgBean) {
        Log.e(TAG, "onSuccessUploadDogAlarm: 上传洗狗机");
    }

    @Override
    public void onFailUploadDogAlarm(Throwable throwable) {

    }

    @Override
    public void onSuccessSyncConfigData(UpLoadGetBean<DogSyncConfigBean> dogSyncConfigBeanUpLoadGetBean) {
        Log.e(TAG, "onSuccessSyncConfigData: 成功拿到同步配置数据" );
        if (dogSyncConfigBeanUpLoadGetBean.getData()!=null){
            Log.e(TAG, "onSuccessSyncConfigData: 成功拿到同步配置数据1111" );
            //如果数据不为空
            DogSyncConfigBean dogSyncConfigBean=dogSyncConfigBeanUpLoadGetBean.getData();
            FlowBean washStepConfigDTO=dogSyncConfigBean.getWashStepConfig();
            List<DogPriceBean> washTypeConfigDTOList=dogSyncConfigBean.getWashTypeConfig();
            DogOtherBean attributeConfigDTO=dogSyncConfigBean.getAttributeConfig();
            long update=dogSyncConfigBean.getUpdateTime();
            PreferenceUtil.commitLong(PreferenceUtil.DOGCONFIGTIME,update);
            handlerStepTime(washStepConfigDTO);
            handlerOtherConfig(attributeConfigDTO);
            handlerFeaturesConfig(washTypeConfigDTOList);
        }
        //在这里进行普通广告的同步
        String upDateTime = PreferenceUtil.getString(PreferenceUtil.SYNCAD, PreferenceUtil.date);
        ArrayMap<String,String> data=getArrayMap(upDateTime);
        data.put(UploadConfig.type,"1");
        mPresenter.getDeviceDataAdvert(data);
    }

    @Override
    public void onFailSyncConfigData(Throwable throwable) {
        Log.e(TAG, "onFailSyncConfigData: 拿取同步数据失败" );
    }

    //同步普通广告成功
    @Override
    public void onSuccessAdvert(UpLoadGetBean<AdvertBean<List<AlarmBean>>> map) {
        if (map!=null && map.getData()!=null){
            String time=map.getData().getTime();
            PreferenceUtil.commitString(PreferenceUtil.SYNCAD, time);
            List<AlarmBean> value = map.getData().getValue();
            sendAdvert(value);
        }
    }

    @Override
    public void onFailAdvert(Throwable throwable) {
        Log.e(TAG, "onFailAdvert: 同步广告数据失败" );
    }

    /**
     * 这个是七牛云上传完成之后返回的值
     * @param key      文件上传保存名称
     * @param info     上传完成返回日志信息
     * @param response 上传完成的回复内容
     */
    @Override
    public void complete(String key, ResponseInfo info, JSONObject response) {
        if (info.isOK()){
            Log.i("tiwolf", "七牛云上传后文件的url=" + response);
            String filePath = response.optString("data");
            // 删除数据表里面的数据
            sqliteManager.delete(filePath);
            //还要去删除文件
            String[] types = filePath.split("\\.");
            if (types.length > 1 && "mp4".equals(types[1])) {
                //说明是历史mp4文件，不删除
                Log.i(TAG, "onThreadFinish: 报警记录七牛云上传后-不删除，我是mp4");
            } else {
                //删掉文件夹的
                Log.i(TAG, "complete: 报警记录七牛云上传后删除文件=" + filePath);
                File file = new File(filePath);
                file.delete();
            }

            if (qiniuFlag){
                //如果是报警的图片
                String imageCreate=uploadItem.getLastModifiedTime();
                Log.i(TAG, "complete: 记录七牛云时间=" + imageCreate.substring(0, 4) + "-" + imageCreate.substring(4, 6) + "-" + imageCreate.substring(6, 8) + " " + imageCreate.substring(8, 10) + ":" + imageCreate.substring(10, 12) + ":" + imageCreate.substring(12));
                Date date = TimeUtil.StrToDateNone(imageCreate);
                String str = TimeUtil.DateToStr(date);
                Log.i(TAG, "complete: 记录七牛云时间=" + str);
                //上传当前警报记录,开始上传文件记录
//                                    policeMap.clear();
//                                    policeMap.put("alarmTime", str);
//                                    policeMap.put("pictureMd5", md5);
//                                    policeMap.put("sn", FlyUtil.getSn(CombinActivity.this));
//                                    handler.sendEmptyMessage(POLICEPITUREUPDATE);
                int netType=0;
                if (filePath.contains("_A_")){
                    netType=1;
                }else if (filePath.contains("_D_")){
                    netType=2;
                }else if (filePath.contains("_E_")){
                    netType=3;
                }else if (filePath.contains("_C_")){
                    netType=4;
                }

                //上传报警记录
                uploadPoliceRecord(str,md5,netType);
            }else{
                //如果不是报警图片，则表明已经走完一个流程。可以继续去上传
                isNotUpload=true;
            }
        }
    }

    private synchronized void getNextUploadRecordHistory(){
        UpdateRecordBean updateRecordBean = sqliteManager.recordCheckByType();
        if (updateRecordBean != null) {
            Log.i(TAG, "getNextUploadRecordHistory: 获取下一条上传日志="+updateRecordBean.getContent());
            if (updateRecordBean.getContentType() == 9) {
                //在这里上传七牛云的文件记录,这里是报警记录，按理说这里只做记录上传。不应该进行穿插文件上传动作
                Log.i(TAG, "getNextUploadRecordHistory: updateFlag="+updateRecordBean.getUpdateFlag()+";type="+updateRecordBean.getContentType()+";updatemg="+updateRecordBean.getUpdateMg()+";updatemsg="+updateRecordBean.getUpdateMsg());
                //只做记录上传
                uploadPoliceRecord(updateRecordBean.getContent(), updateRecordBean.getUpdateMsg(),1);

            } else if (updateRecordBean.getContentType() == 8) {
                //在这里上传七牛云的文件记录
                Message message1 = handler.obtainMessage();
                message1.what = RECORDUPLOAD;
                message1.obj = updateRecordBean.getContent() + "," + updateRecordBean.getUpdateMsg();
                handler.sendMessage(message1);
            } else if (updateRecordBean.getContentType() == 2) {
                Message message1 = handler.obtainMessage();
                message1.what = RECORDDEL;
                message1.obj = updateRecordBean.getContent();
                handler.sendMessage(message1);
            } else if (updateRecordBean.getContentType() == 10) {
                //在这里进行文件的合并，因为这个合并成功就会继续搞上传的。并没有继续记录上传的延续
                Message message1 = handler.obtainMessage();
                message1.what = MERGE;
                message1.obj = updateRecordBean.getUpdateMsg();
                handler.sendMessage(message1);
            } else if (updateRecordBean.getContentType() == 1) {
                Message message1 = handler.obtainMessage();
                message1.what = RECORDDEL;
                message1.obj = updateRecordBean.getContent();
                handler.sendMessage(message1);
            }
        }
    }

    /**
     *
     * @param time 上传时间
     * @param md5 图片md5
     * @param type 报警类型
     */
    private synchronized void uploadPoliceRecord(String time,String md5,int type){
        if (policeMap==null){
            policeMap=new ArrayMap<>();
        }
        policeMap.clear();
        policeMap.put("alarmTime", time);
        policeMap.put("pictureMd5", md5);
        policeMap.put("alarmType",type+"");
        policeMap.put("sn", FlyUtil.getSn(DogActivity.this));
        handler.sendEmptyMessage(POLICEPITUREUPDATE);
    }

    private synchronized ArrayMap<String,String> getArrayMap(String upDateTime){
        if (sycnDataMap==null){
            sycnDataMap=new ArrayMap<>();
        }
        sycnDataMap.clear();
        sycnDataMap.put(UploadConfig.endUser, "DEVICELIG");
        sycnDataMap.put(UploadConfig.sn, FlyUtil.getSn(DogActivity.this));
        sycnDataMap.put(UploadConfig.UPDATETIME, upDateTime);
        return (ArrayMap<String, String>) sycnDataMap;
    }


    @Override
    public void onCompletion(MediaPlayer mediaPlayer) {
        /**
         * 其中 LoudItems为广播列表，playItems为音视频列表
         * loadInt为广播列表播放序列，playNum为广播整个列表播放次数
         *
         */
        try {
            if (playItems != null && playItems.size() >= 1) {
                //主线程
                Log.i(TAG, "startPlay onCompletion222211: 音视频文件是否有问题"+mediaPlayer.isLooping());
            } else {
                //上面说明playItems已经为空或者是playItems队列出现问题，要么重新初始化全部闹钟，要么重新获取列表，然后得到playItems
                //直接获取列表会比较好，而且不会显得唐突。获取到列表之后则直接播放下一首
                Log.i(TAG, "startPlay onCompletion2222: 音视频文件已经有问题"+mediaPlayer.isLooping());
                playItems = playItemBackpackages;
                isplayIn = true;
            }
            mediaPlayer.reset();
        } catch (Exception e) {
            Log.i(TAG, "startPlay onCompletion: 异常" + e.getMessage());
        }
        //播放完成，进行下一首
        cacheLinkedDeque1.add("010bo");
        synchronized (receiveObject) {
            receiveObject.notifyAll();
        }

    }

    @Override
    public boolean onError(MediaPlayer mediaPlayer, int what, int extra) {

        Log.i(TAG, "startPlay onError: 播放出错66;mediaPlayer=" + mediaPlayer.isPlaying() + ";mPlayer=" + mPlayer.isPlaying() + ";errorCode=" + what + "error1=" + extra);
        mediaPlayer.reset();
        if (playItems == null) {
            isPlay = true;//出现问题，则重新添加文件
        }
        if (isLiveFlag){
            isLiveFlag=false;
            isInFreeAdFlag=true;
        }

        if (what == 1 && extra == -2147483648) {
            //网络加载出现error (1, -2147483648) 也就是mediaplayer 初始化失败
            //反复的创建mMediaplayer 同样也会出现(1, -2147483648)
        } else if(what==1 && extra==0){

            //这说明播放文件出现问题了
            if (currentFile!=null){
                cacheLinkedDeque1.add("024");
                synchronized (receiveObject) {
                    receiveObject.notifyAll();
                }

            }


        }else {
//            playMediaFile(playInt);
            //这个还得做个判断,如果是一开始就有直播列表，不管是不是直播导致的问题，只要出现了。那就重新刷新列表
            fromLiveFlag=true;
            //如果开机就有直播列表，出错则需要重新获取广告列表
            cacheLinkedDeque1.add("008");
            synchronized (receiveObject) {
                receiveObject.notifyAll();
            }


        }

        return true; // 返回true表示在此处理错误，不会回调onCompletion
    }

    private void setUploadFile(String i) {
        cacheLinkedDeque.add(i);
        synchronized (uploadLock) {
            uploadLock.notifyAll();
        }
    }

    /**==================警告弹窗=====================*/
    private void getWarnDiglog(){
        if (warnDialog==null){
            warnDialog=new WarnDialog();
        }
    }

    private void showUrgenDialog(){
        getWarnDiglog();
        warnDialog.showUrgenDialog(DogActivity.this,DogActivity.this);
    }

    private void dismissUrgenDialog(){
        getWarnDiglog();
        warnDialog.dismissUrgenDialog();
    }



    /**==================支付弹窗======================*/
    private void getPayDialogUtil(){
        if (payDialogUtil==null){
            payDialogUtil=new PayDialogUtil(DogActivity.this, DogActivity.this);
        }
    }

    /**==================一键洗狗支付功能=======================*/
    private void dismissPayOneDialog(){
        getPayDialogUtil();
        payDialogUtil.dismissPayOnedialog();
    }

    private void showPayOneDialog(){
        getPayDialogUtil();
        boolean flag=payDialogUtil.showPayOneDialog(DogActivity.this,DogActivity.this);
        if (flag){
            dogWashType=DogWashType.ONEKEYWASH;
            handler.sendEmptyMessage(DOGPAYURL);
//            getPayUrl(DogWashType.ONEKEYWASH);
        }
    }

    private void changePayOneMsg(Bitmap bitmap,String orderNo,double amount){
        getPayDialogUtil();
        payDialogUtil.changePayOneMsg(bitmap,orderNo,amount);
    }
    /**==================高端洗狗特征功能=======================*/
    private void dismissDogcharacterDialog(){
        getPayDialogUtil();
        payDialogUtil.dismissPayOnedialog();
    }

    private void showDogcharacterDialog(){
        getPayDialogUtil();
        payDialogUtil.showDetailDialog(
                DogActivity.this,
                DogActivity.this,
                smallDogPrice, midDogPrice, bigDogPrice,
                shortHairPrice,normalLongHairPrice, longHairPrice,
                thinHairPrice,normalHairPrice,thickHairPrice,
                washDryPrice,dryDogPrice,
                oneWaterInt,bodyWashInt,twoWaterInt,conditionerInt,threeWaterInt,preheatInt,dryInt,detailWashPrice
                );
    }

    private void changeDogcharacterMsg(Bitmap bitmap,String orderNo,double amount){
        getPayDialogUtil();
        payDialogUtil.changePayOneMsg(bitmap,orderNo,amount);
    }
    /**==================高端洗狗支付功能=======================*/
    private void dismissPayDialog(){
        getPayDialogUtil();
        payDialogUtil.dismissPaydialog();
    }

    private void showPayDialog(){
        getPayDialogUtil();
        payDialogUtil.showPayDialog(DogActivity.this,DogActivity.this);
    }

    private void changePayMsg(Bitmap bitmap,String orderNo,double amount){
        getPayDialogUtil();
        payDialogUtil.changePayMsg(bitmap,orderNo,amount,doyType,hairType,hairthick,washTp,tem);
    }
    /**==================支付成功后功能=======================*/
    private void dismissPaySuccessDialog(){
        getPayDialogUtil();
        payDialogUtil.dismissPaySuccessDialog();
    }

    private void showPaySuccessDialog(){
        getPayDialogUtil();
        payDialogUtil.showPaySuccessDialog(DogActivity.this,DogActivity.this,order_No,order_amount,washContent);
    }

    private void existFullscreenAds() {
        //1.设置R.id.main 的布局、size
        LinearLayout main = findViewById (R.id.main);
        RelativeLayout.LayoutParams mainLP = (RelativeLayout.LayoutParams) main.getLayoutParams();
        mainLP.width = LinearLayout.LayoutParams.MATCH_PARENT;
        mainLP.height = LinearLayout.LayoutParams.WRAP_CONTENT;
        main.setLayoutParams(mainLP);

        //2.设置广告fragment的布局、size
        FrameLayout adF = findViewById (R.id.adFragment);
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) adF.getLayoutParams();

        final int h = DisplayUtil.dpToPx(this, 434f);//dp转换成px
        final int w = DisplayUtil.dpToPx(this,610f);//dp转换成px
        lp.height =h;
        lp.width = w;

        final int l = DisplayUtil.dpToPx(this,16f);
        final int r = DisplayUtil.dpToPx(this, 3f);
        final int t = DisplayUtil.dpToPx(this, 22);
        final int b = DisplayUtil.dpToPx(this, 18);
        adF.setPadding(l,t,r,b);
        adF.setLayoutParams(lp);

        //3.设置 R.id.up 容器的布局、size
        RelativeLayout up = findViewById (R.id.up);
        LinearLayout.LayoutParams upLP = (LinearLayout.LayoutParams) up.getLayoutParams();
        final int upH = DisplayUtil.dpToPx(this,610f);//dp转换成px
        upLP.width = upH;
        upLP.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        upLP.topMargin = DisplayUtil.dpToPx(this, 120f);
        upLP.leftMargin = DisplayUtil.dpToPx(this, 130f);
        up.setLayoutParams(upLP);

        //4.隐藏广告fragment外框背景
        findViewById(R.id.frontIv).setVisibility(View.VISIBLE);

        //5.隐藏右上角二维码入口
        findViewById(R.id.qrcode_iv).setVisibility(View.GONE);
        infoLl.setVisibility(View.GONE);

        final TextView versionTv = findViewById(R.id.version1);
        versionTv.setVisibility(View.VISIBLE);
        versionTv.setText(appVersion);
    }

    private void enterFullscreenAds() {
        //1.设置R.id.main 的布局、size
        LinearLayout main = findViewById (R.id.main);
        RelativeLayout.LayoutParams mainLP = (RelativeLayout.LayoutParams) main.getLayoutParams();
        mainLP.width = LinearLayout.LayoutParams.MATCH_PARENT;
        mainLP.height = LinearLayout.LayoutParams.MATCH_PARENT;
        main.setLayoutParams(mainLP);

        //2.设置广告fragment的布局、size
        FrameLayout adF = findViewById(R.id.adFragment);
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) adF.getLayoutParams();
        adF.setPadding(0,0,0,0);
        lp.width = FrameLayout.LayoutParams.MATCH_PARENT;
        lp.height = FrameLayout.LayoutParams.MATCH_PARENT;
        adF.setLayoutParams(lp);

        //3.设置R.id.up 容器的布局、size
        RelativeLayout up = findViewById (R.id.up);
        LinearLayout.LayoutParams upLP = (LinearLayout.LayoutParams) up.getLayoutParams();
        upLP.width = LinearLayout.LayoutParams.MATCH_PARENT;
        upLP.height = LinearLayout.LayoutParams.MATCH_PARENT;
        upLP.leftMargin = 0;
        upLP.topMargin = 0;

        up.setLayoutParams(upLP);

        //4.隐藏广告fragment外框背景
        findViewById(R.id.frontIv).setVisibility(View.GONE);

        findViewById(R.id.qrcode_iv).setVisibility(View.VISIBLE);
        final TextView versionTv = findViewById(R.id.version1);
        versionTv.setVisibility(View.GONE);
    }


//    private String[] dogtypes;
//    private String[] dogHairLongs;
//    private String[] dogHairThins;
//    private String[] dogWashTypes;
//    private IndicatorSeekBar temIs;
//    private RadioGroup dogRg,hairRg,thinRg,washRg;
//    private TextView washTimeTv,washMoneyTv;
//    private TextView submitTv,cancelTv;
//    private int totalTime;
//    private double totalMoney;
//    private String dogTypeStr,hairLongStr,hairLessStr,washTypeStr;//爱犬类型，毛发类型，稀疏程度，洗宠类型
//    private double chooseInt1,chooseInt2,chooseInt3,chooseInt4;
//    CustomDialog detailDialog;
//    boolean detailFlag=false;
//    private synchronized void showDetailDialog(){
//        if (detailDialog!=null && detailDialog.isShowing()){
//            return;
//        }
//        View view=getLayoutInflater().inflate(R.layout.dialog_detail_dog,null);
//        detailDialog=new CustomDialog(this,1536,864,view,R.style.DialogTheme);
//        temIs=detailDialog.findViewById(R.id.tem_is);
//        dogRg=detailDialog.findViewById(R.id.dog_rg);
//        hairRg=detailDialog.findViewById(R.id.hair_rg);
//        thinRg=detailDialog.findViewById(R.id.thin_rg);
//        washRg=detailDialog.findViewById(R.id.wash_rg);
//        washTimeTv=detailDialog.findViewById(R.id.wash_time_tv);
//        washMoneyTv=detailDialog.findViewById(R.id.wash_money_tv);
//        submitTv=detailDialog.findViewById(R.id.character_submit_tv);
//        cancelTv=detailDialog.findViewById(R.id.character_cancel_tv);
//
//        chooseInt1=midDogPrice;
//        chooseInt2=normalLongHairPrice;
//        chooseInt3=normalHairPrice;
//        chooseInt4=washDryPrice;
//
//        dogRg.check(R.id.mid_rb);
//        hairRg.check(R.id.normal_hair_rb);
//        thinRg.check(R.id.normal_rb);
//        washRg.check(R.id.washdry_rb);
//
//        dogTypeStr=dogtypes[1];
//        hairLongStr=dogHairLongs[1];
//        hairLessStr=dogHairThins[1];
//        washTypeStr=dogWashTypes[1];
//        getWashTime();
//
//
//        dogRg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
//            @Override
//            public void onCheckedChanged(RadioGroup group, int checkedId) {
//                switch (checkedId){
//                    case R.id.small_rb:{
//                        Log.e(TAG, "onCheckedChanged: 点击了小型犬" );
//                        chooseInt1=smallDogPrice;
//                        dogTypeStr=dogtypes[0];
//                        getWashTime();
//                        break;
//                    }
//                    case R.id.mid_rb:{
//                        Log.e(TAG, "onCheckedChanged: 点击了中型犬" );
//                        chooseInt1=midDogPrice;
//                        dogTypeStr=dogtypes[1];
//                        getWashTime();
//                        break;
//                    }
//                    case R.id.big_rb:{
//                        Log.e(TAG, "onCheckedChanged: 点击了大型犬" );
//                        chooseInt1=bigDogPrice;
//                        dogTypeStr=dogtypes[2];
//                        getWashTime();
//                        break;
//                    }
//                }
//            }
//        });
//
//        hairRg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
//            @Override
//            public void onCheckedChanged(RadioGroup group, int checkedId) {
//                switch (checkedId){
//                    case R.id.short_hair_rb:{
//                        Log.e(TAG, "onCheckedChanged: 选择了短毛" );
//                        chooseInt2=shortHairPrice;
//                        hairLongStr=dogHairLongs[0];
//                        getWashTime();
//                        break;
//                    }
//                    case R.id.normal_hair_rb:{
//                        Log.e(TAG, "onCheckedChanged: 选择了一般毛发" );
//                        chooseInt2=normalLongHairPrice;
//                        hairLongStr=dogHairLongs[1];
//                        getWashTime();
//                        break;
//                    }
//                    case R.id.long_hair_rb:{
//                        Log.e(TAG, "onCheckedChanged: 选择了长毛发" );
//                        chooseInt2=longHairPrice;
//                        hairLongStr=dogHairLongs[2];
//                        getWashTime();
//                        break;
//                    }
//                }
//            }
//        });
//
//        thinRg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
//            @Override
//            public void onCheckedChanged(RadioGroup group, int checkedId) {
//                switch (checkedId){
//                    case R.id.thin_rb:{
//                        Log.e(TAG, "onCheckedChanged: 选择了薄毛" );
//                        chooseInt3=thinHairPrice;
//                        hairLessStr=dogHairThins[0];
//                        getWashTime();
//                        break;
//                    }
//                    case R.id.normal_rb:{
//                        Log.e(TAG, "onCheckedChanged: 选择了一般厚毛发" );
//                        chooseInt3=normalHairPrice;
//                        hairLessStr=dogHairThins[1];
//                        getWashTime();
//                        break;
//                    }
//                    case R.id.thick_rb:{
//                        Log.e(TAG, "onCheckedChanged: 选择了厚毛发" );
//                        chooseInt3=thickHairPrice;
//                        hairLessStr=dogHairThins[2];
//                        getWashTime();
//                        break;
//                    }
//                }
//            }
//        });
//
//        washRg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
//            @Override
//            public void onCheckedChanged(RadioGroup group, int checkedId) {
//                switch (checkedId){
//                    case R.id.washdry_rb:{
//                        Log.e(TAG, "onCheckedChanged: 选择了烘洗一体" );
//                        chooseInt4=washDryPrice;
//                        washTypeStr=dogWashTypes[1];
//                        getWashTime();
//                        break;
//                    }
//                    case R.id.dry_rb:{
//                        Log.e(TAG, "onCheckedChanged: 选择了烘干" );
//                        chooseInt4=dryDogPrice;
//                        washTypeStr=dogWashTypes[0];
//                        getWashTime();
//                        break;
//                    }
//
//                }
//            }
//        });
//
//        submitTv.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (detailDialog.isShowing()){
//                    detailDialog.dismiss();
//                }
//                totalMul=chooseInt1*chooseInt2*chooseInt3*chooseInt4;
//                Log.e(TAG, "onClick: 高端精洗当前的倍数="+totalMul );
//                dogWashType=DogWashType.DETAILWASH;
//                handler.sendEmptyMessage(DOGPAYURL);
////                getPayUrl(DogWashType.DETAILWASH);
//                showPayDialog();
//            }
//        });
//
//        cancelTv.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (detailDialog.isShowing()){
//                    detailDialog.dismiss();
//                }
//            }
//        });
//
//        temIs.setIndicatorTextFormat("当前温度为 ${TICK_TEXT} °");
//        detailDialog.show();
//        detailDialog.setCancelable(true);
//
//    }
//
//    private void getWashTime(){
//        totalTime=(int)((oneWaterInt+bodyWashInt+twoWaterInt+conditionerInt+threeWaterInt+preheatInt+dryInt+disinfectantInt+windChangeInt+fourWaterInt)*(chooseInt1*chooseInt2*chooseInt3*chooseInt4)/1000.0/60.0);
//        totalMoney=detailWashPrice*(chooseInt1*chooseInt2*chooseInt3*chooseInt4);
//        DecimalFormat df = new DecimalFormat ("#.00");
//        String moneyStr = df.format (totalMoney);
//        washTimeTv.setText(""+totalTime);
//        washMoneyTv.setText(moneyStr);
//        totalMoney=Double.valueOf(moneyStr);
//    }

    private void setTFcardErrorWarning(int warnCode){

        Log.i(TAG, "setTFcardErrorWarning: 上传错误时，tfcardErrorFlag="+tfcardErrorFlag+";warnCode="+warnCode+";sdcardCode="+sdcardErrorCode );
        if (warnCode==1){
            if (tfcardErrorFlag){
                setMainBoardErrorWarning(warnCode);
            }

        }else if (warnCode==0){
            if (!tfcardErrorFlag){
                setMainBoardErrorWarning(warnCode);
            }
        }

    }

    private void setMainBoardErrorWarning(int errorCode){
        getErrorMap().clear();
        errorMap.put("sn", FlyUtil.getSn(this));
        if(errorCode==1){
            //tfcard有问题
            errorMap.put("tf","-1");
        }else if(errorCode==0){
            errorMap.put("tf","1");
        }
        handler.sendEmptyMessage(UPERROR);
    }

    public void threadPoolUploadFile(String poll){
//        Log.i(TAG, "threadPoolUploadFile: 七牛云文件记录上传出现="+isNotUpload+";"+poll );
        //先查询是否有需要下载的文件
        if ("2".equals(poll)) {

            if (!isdownloadFlag){//是否在可下载状态
                return;
            }

            /**
             * ==============================在七牛云服务器下面运行====================================
             */
            ArrayList<DownloadItem> downloadItems = sqliteManager.downloadFlagCheck("1");
            Log.i(TAG, "threadPoolUploadFile: 下载获取到的列表值========="+downloadItems.size() );
            if (downloadItems.size() > 0) {
                Log.i(TAG, "threadPoolUploadFile: 七牛云下载文件开始");
                qiniuDownloadFile(downloadItems.get(0).getDownloadMd5());
            } else {
                isdownloadFlag = true;
                //如果已经下载完，那么应该将数值提高到20分钟再来查询
                isdownloadInt=18*60;
            }

        } else if (poll.startsWith("http")) {
            Log.i(TAG, "threadPoolUploadFile 七牛云: " + poll);
            //说明这个是上传到七牛云的,因为七牛云的是一整个url地址
            String md5 = poll.substring((poll.lastIndexOf("=") + 1), poll.lastIndexOf("."));
            Log.i(TAG, "download:3单个未下载的文件全部去下载 七牛云服务器 " + md5);
            if (md5!=null && md5.length() == 32) {
                Log.i(TAG, "download:3单个未下载的文件全部去下载,,,,,md5正确，可以去下载 七牛云服务器" + md5);
//                sqlInt = 0;
                DownloadItem downloadItem = sqliteManager.downloadIdCheck(md5);
                if (downloadItem != null && downloadItem.getDownloadMd5()!=null) {
                    //说明表里有，进行状态判断，如果是3，则表示正在下载中
                    Log.i(TAG, "threadPoolUploadFile:七牛云服务器 flag=" + downloadItem.getDownloadFlag() +"sdPath="+sdPath+ ";ext=" + downloadItem.getDownloadExt()+" url=" + poll );
                    String fileName = downloadItem.getDownloadName();
                    String path=TestConfig.downloadFilePath+fileName;
                    Log.e(TAG, "threadPoolUploadFile: 七牛云服务器 path="+path );
                    File file;
                    if (sdPath == null || sdPath.length() == 0) {
                        file = new File(TestConfig.downloadFilePath + fileName);
                    } else {
                        file = new File(sdPath + "/solar/download/" + fileName);
                    }

                    if (downloadItem.getDownloadFlag() == 1 || !file.exists()) {
                        //1,表示未下载或者下载中
                        //先去文件夹里面对文件查询一次
                        Log.i(TAG, "startplay: 准备去下载 七牛云服务器");

                        boolean fileCanCreateFlag=true;
                        if (!file.exists()) {
                            try {
                                file.createNewFile();
                                setTFcardErrorWarning(0);
                            } catch (IOException e) {
                                e.printStackTrace();
                                //文件无法创建
                                fileCanCreateFlag=false;
                                //tf卡创建出现io异常
                                setTFcardErrorWarning(1);
                            }
                        }
                        if (fileCanCreateFlag){
                            threadPoollExcutorUtil.qiniuDownloadFile(poll, file, downloadItem, sqliteManager);
                        }else{
                            //如果文件都无法创建，则将这条下载记录删除
                            sqliteManager.deleteDownloadItem(md5);
                            isdownloadFlag=true;
                        }
                    } else if(downloadItem.getDownloadFlag()==3){
                        Log.i(TAG, "threadPoolUploadFile: 文件正在下载中");
                    }else{
                        Log.i(TAG, "startplay: 已经下载完 七牛云服务器");
                        isdownloadFlag = true;
                    }

                } else {
                    isdownloadFlag = true;
                }
            } else {
                isdownloadFlag = true;
            }


        } else {
            Log.i(TAG, "threadPoolUploadFile: 上传和下载出现其他异常=" + poll);
            isdownloadFlag = true;
        }


    }



    @Override
    public boolean onInfo(MediaPlayer mp, int what, int extra) {
        return false;
    }

    @Override
    public void onPrepared(MediaPlayer mediaPlayer) {
        Log.i(TAG, "startPlay onPrepared: 广告准备好了"+isLiveFlag);

        if (isLiveFlag) {        //如果是直播源，那么直接播放。定时播放的时候，也应该先stop,然后reset
            Log.i(TAG, "receiveWork: 直播准备好开始播放");
            int liveWidth = mediaPlayer.getVideoWidth();
            int libeHeight = mediaPlayer.getVideoHeight();
            Log.i(TAG, "onPrepared: 直播的宽=" + liveWidth + ";高=" + libeHeight);
            mediaPlayer.start();
        } else {
            playFailInt++;
            mediaPlayer.start();

        }
        Message message1=handler.obtainMessage();
        message1.what=WARNSHOW;
        message1.arg1=2;
        handler.sendMessage(message1);

    }

    @Override
    public void onSeekComplete(MediaPlayer mediaPlayer) {
//        Log.i(TAG, "startPlay onSeekComplete: 播放信息 寻找完成");
        int liveWidth = mediaPlayer.getVideoWidth();
        int libeHeight = mediaPlayer.getVideoHeight();
        Log.i(TAG, "onSeekComplete: 直播的宽=" + liveWidth + ";高=" + libeHeight);

    }

    @Override
    public void onVideoSizeChanged(MediaPlayer mediaPlayer, int width, int height) {
//        Log.i(TAG, "startPlay onVideoSizeChanged: 播放信息 播放尺寸变化");
        int liveWidth = mediaPlayer.getVideoWidth();
        int libeHeight = mediaPlayer.getVideoHeight();
        Log.i(TAG, "onVideoSizeChanged: 直播的宽=" + liveWidth + ";高=" + libeHeight);
        Log.i(TAG, "onVideoSizeChanged: 直播的宽111=" + width + ";高=" + height);

    }

    @Override
    public void getCountDownTime(int time) {
        Log.i(TAG, "timeOver: 还有多少秒结束" + time);
    }

    @Override
    public void timeOver() {
        Log.i(TAG, "timeOver: 倒计时结束"+isLiveFlag);
        if (!isLiveFlag){
            cacheLinkedDeque1.add("010bo");
            synchronized (receiveObject) {
                receiveObject.notifyAll();
            }
        }
    }


    // 闹钟返回
    @Override
    public void receiveAlarmMsg(String message, boolean flag) {
        Log.i(TAG, "收到接收者返回的信息" + message);
        if ("-100".equals(message) || "-200".equals(message) ) {

            canRecordFlag=true;
            cacheLinkedDeque1.add("006");
            synchronized (receiveObject) {
                receiveObject.notifyAll();
            }
            Log.i(TAG, "Event: 闹钟返回来的信息--是存储" + message);

            /**
             * 定时视频进行处理
             */
            //过了3分钟关闭

//            Log.i(TAG, "Event: 录制了一个视频"+message );
        }/**
         * 以200为分界线，小于200大于0则为广告列表，大于等于200并且小于等于300则为广播
         */
        else {
            //这个是广告
            if (!isLiveFlag) {
                cacheLinkedDeque1.add("007" + message);
                synchronized (receiveObject) {
                    receiveObject.notifyAll();
                }
            }

        }
    }

    /**
     * =========================TTS配置状态 startlistener=========================TextToSpeech.OnInitListener
     */
    @Override
    public void onInit(int status) {
        // TTS初始化
        if (status == TextToSpeech.SUCCESS) {
            Log.i(TAG, "onInit: 开关屏的时候出现的tts初始化" );
            //设置音调，1.0是常规
            textToSpeech.setPitch(1.0f);
            //设定语速，默认1.0正常语速
            textToSpeech.setSpeechRate(1.0f);
            if ("zh".equals(sLanguage)) {
                int result = textToSpeech.setLanguage(Locale.CHINESE);
                if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                    Log.i("tiwolf", "onInit: 数据丢失或者不支持");
                }
            } else {
                int result = textToSpeech.setLanguage(Locale.ENGLISH);
                if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                    Log.i("tiwolf", "onInit: 数据丢失或者不支持");
                }
            }

        }else{
            Log.i(TAG, "onInit: tts初始化失败");
        }
    }

    @Override
    public void oneKeyWash() {
        if (!waterLevelFlag){
            //水位过低
            Log.e(TAG, "oneKeyWash: 水位低，当前无法洗狗");
            setMechineWaterLevelWarn("水位过低，当前正在加水中，请稍等。。。");
            return;
        }
        if (waterTem<lowerWater){
            //水位过低
            Log.e(TAG, "oneKeyWash: 水温低，当前无法洗狗");
            setMechineWaterTemWarn("水温过低，当前正在加热中，请稍等");
            return;
        }
        if (waterTem>(upperWater+2)){
            //水温过高
            Log.e(TAG, "oneKeyWash: 水温过高，当前无法洗狗");
            setMechineWaterTemWarn("水温过高，当前无法洗狗，请稍等");
            return;
        }

        Log.e(TAG, "oneKeyWash: 从CommandFragment碎片返回一键洗狗");
        washContent="一键洗狗";
        showPayOneDialog();
        totalMul=1;


    }

    @Override
    public void detailWash() {
        Log.e(TAG, "oneKeyWash: 从CommandFragment碎片返回高端洗狗");
        if (!waterLevelFlag){
            //水位过低
            Log.e(TAG, "oneKeyWash: 水位低，当前无法洗狗");
            setMechineWaterLevelWarn("水位过低，当前正在加水中，请稍等。。。");
            return;
        }
        if (waterTem<lowerWater){
            //水位过低
            Log.e(TAG, "oneKeyWash: 水温低，当前无法洗狗");
            setMechineWaterTemWarn("水温过低，当前正在加热中，请稍等");
            return;
        }
        if (waterTem>(upperWater+2)){
            //水温过高
            Log.e(TAG, "oneKeyWash: 水温过高，当前无法洗狗");
            setMechineWaterTemWarn("水温过高，当前无法洗狗，请稍等");
            return;
        }
        washContent="高端洗狗";
        showDogcharacterDialog();
//        showDetailDialog();
//        showPayDialog();
//        getPayUrl(DogWashType.DETAILWASH);
    }

    @Override
    public void dogShop() {
        ToastUtils.toast(DogActivity.this,"当前功能还未开放，敬请期待");
        Log.e(TAG, "oneKeyWash: 从CommandFragment碎片返回洗狗机商店");
    }


    /**
     * tts回调
     */
    private class TtsProgress extends UtteranceProgressListener {

        //非主线程
        @Override
        public void onStart(String s) {
//            Log.i(TAG, "======onStart: 开始" );
            Log.i(TAG, "onStart:获取当前的音量值11 ");
            if (mPlayer != null && speakIsStart) {
                mPlayer.setVolume(0f, 0f);
                Log.i(TAG, "onStart:获取当前的音量值11= " + vv.isPlaying() + ";vv是否已经停止=" + isVvOnPlay);
                if (!vv.isPlaying()) {
                    currentVolumn = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
                    Log.i(TAG, "onStart:获取当前的音量值===声音 " + currentVolumn);
                }

//                        Log.i(TAG, "onReceive: 当前声音"+currentVolumn );

                //得到当前音量大小
                if (isVolumeOn) {
                    audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, fixedVolume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
                } else {
                    audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, avVolumn, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
                }

            }



        }

        @Override
        public void onDone(String s) {
            warnMsg = "";
            speakTime--;
            Log.i(TAG, "======onDone: 结束" + speakTime);
            if (speakTime > 0 && speakContent != null && speakContent.length() != 0 && !vv.isPlaying()) {
                Log.i(TAG, "onDone: 继续播放");
                speakIsStart = false; //主要是为了多次播放，第二次不会再进行音量更改

                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                speakOut(speakContent);

            } else {
                avAlarmId = -1;
                speakIsStart = true;
                if (mPlayer != null && !vv.isPlaying()) {
                    Log.i(TAG, "onPrepared: 已经将声音释放onDone");
                    if (playItems == null && !isLiveFlag) {
                        currentVolumn = 0;
                    }

                    Log.i(TAG, "onPrepared: 已经将声音释放onDone 000=" + currentVolumn);
                    if (isVolumeOn) {
                        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, fixedVolume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
                    } else {
                        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolumn, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
                    }

                    mPlayer.setVolume(1f, 1f);

                    handler.sendEmptyMessage(SCREENVOLUME);
                }
                //需要判断是否有播放阶段广告
                //如果是蓝牙音箱的情况下，需要不在ai，直播，和广告的情况下才会切回到蓝牙音箱那边



                speakContent = null;
            }
        }

        @Override
        public void onError(String s) {
            Log.i(TAG, "======onError: 错误" );
            warnMsg = "";
            avAlarmId = -1;
            speakTime = 0;
            speakIsStart = true;

            if (mPlayer != null && !vv.isPlaying()) {
                Log.i(TAG, "onPrepared: 已经将声音释放onError");
                if (playItems == null) {
                    currentVolumn = 0;
                }

                Log.i(TAG, "onPrepared: 已经将声音释放onError===" + currentVolumn);
                if (isVolumeOn) {
                    audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, fixedVolume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
                } else {
                    audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolumn, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
                }

                mPlayer.setVolume(1f, 1f);
                handler.sendEmptyMessage(SCREENVOLUME);
            }
            //需要判断是否有播放阶段广告
            //如果是蓝牙音箱的情况下，需要不在ai，直播，和广告的情况下才会切回到蓝牙音箱那边

        }

        @Override
        public void onStop(String utteranceId, boolean interrupted) {
            super.onStop(utteranceId, interrupted);
            Log.i(TAG, "onPrepared: 已经将声音释放onStop000");
            warnMsg = "";
            speakTime = 0;
            avAlarmId = -1;
            speakIsStart = true;

            Log.i(TAG, "onPrepared: 已经将声音释放onStop111" + mPlayer + ";" + vv.isPlaying() + ";" + isVvOnPlay);
            if (mPlayer != null && !vv.isPlaying() && !isVvOnPlay) {
                Log.i(TAG, "onPrepared: 已经将声音释放onStop222");
                if (playItems == null) {
                    currentVolumn = 0;
                }
                Log.i(TAG, "onPrepared: 已经将声音释放onStop222===" + currentVolumn);
                if (isVolumeOn) {
                    audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, fixedVolume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
                } else {
                    audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolumn, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
                }

                mPlayer.setVolume(1f, 1f);
                handler.sendEmptyMessage(SCREENVOLUME);
            }

        }
    }

    private void speakOut(String strSpeak) {
        Log.i(TAG, "speakOut: 开关屏的时候出现了tts" );
        if (textToSpeech != null && !textToSpeech.isSpeaking()) {
            textToSpeech.speak(strSpeak, TextToSpeech.QUEUE_ADD, null, "UniqueID");//这个方法是异步的
        }
    }

    private int avVolumn1 = 12;
    public void speakWarning(String str) {
        speakTime=1;
        if (PreferenceUtil.getBoolean(PreferenceUtil.RESPONSEFLAG, false)) {
//            speakIsStart=true;
            Log.i(TAG, "speakWarning: 播放提醒语音");
            if (!vv.isPlaying() && speakIsStart) {
                avVolumn = avVolumn1;
                String content = str;
//                Log.i(TAG, "speakWarning: 文本转语音进来了" );
                speakOut(content);
            }
//            Log.i(TAG, "speakWarning: 文本转语音进来了1111" );
        }
    }

    public void speakDogStateWarn(String str) {
        speakTime=1;
        Log.i(TAG, "speakWarning: 播放洗狗机提醒语音="+str);
        if(textToSpeech.isSpeaking()){
            Log.i(TAG, "speakWarning: 当前正在播放的时候，需要关闭当前播放的");
            textToSpeech.stop();
            Log.i(TAG, "speakWarning: 当前正在播放的时候，需要关闭当前播放的1111="+speakIsStart);
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        if (!vv.isPlaying() && speakIsStart) {
            avVolumn = avVolumn1;
            String content = str;
//                Log.i(TAG, "speakWarning: 文本转语音进来了" );
            speakOut(content);
        }
    }

    /**
     * =========================TTs状态 endlistener=========================TextToSpeech.OnInitListener
     */

    /**
     * =========================摄像头返回 startListener=========================ICameraListener
     */
    @Override
    public void setPictureParams(String picMd5, String date, int policeType) {

    }

    @Override
    public void setMp4Params(String mp4Md5, String mp4Name) {

    }

    @Override
    public void isHasPic(boolean flag) {

    }

    @Override
    public void operationBack(String msg) {

    }


    @Override
    public void setPeopleDo(boolean flag) {

    }

    @Override
    public void setError(int code) {

    }

    @Override
    public void isCanCreateRecord(boolean flag) {
        canRecordFlag=flag;
    }

    @Override
    public void setRecordPicture(String pictureName) {
        Message message1 = handler.obtainMessage();
        message1.what = RECORDUPLOAD;
        message1.obj = pictureName;
        handler.sendMessage(message1);
    }
/**
 * =========================摄像头返回 endListener=========================ICameraListener
 */

    @Override
    public void sendMsgToActivity(String key, Object value, String time) {
        switch (key){
            case ActivityConfig.DOGBOXCONFIG:{
                long timelo=Long.valueOf(time);
                PreferenceUtil.commitLong(PreferenceUtil.DOGCONFIGTIME,timelo);
                List<DogPriceBean> dogPriceBeanList= (List<DogPriceBean>) value;
                handlerFeaturesConfig(dogPriceBeanList);

                break;
            }
            case ActivityConfig.DOGBOXFLOWCONFIG:{
                long timelo=Long.valueOf(time);
                PreferenceUtil.commitLong(PreferenceUtil.DOGCONFIGTIME,timelo);
                FlowBean flowBean= (FlowBean) value;
                handlerStepTime(flowBean);

                break;
            }
            case ActivityConfig.DOGBOXOTHERCONFIG:{
                long timelo=Long.valueOf(time);
                PreferenceUtil.commitLong(PreferenceUtil.DOGCONFIGTIME,timelo);
                DogOtherBean dogOtherBean= (DogOtherBean) value;
                handlerOtherConfig(dogOtherBean);


                break;
            }

        }

    }

    private void handlerStepTime(FlowBean flowBean){
        oneWaterInt= (int) flowBean.getStep1();
        bodyWashInt= (int) flowBean.getStep2();
        if (flowBean.getSoapUseTime()>0){
            bodyWashInt1= (int) flowBean.getSoapUseTime()*1000;
        }
        twoWaterInt= (int) flowBean.getStep3();
        conditionerInt= (int) flowBean.getStep4();
        if (flowBean.getConditionerUseTime()>0){
            conditionerInt1= (int) flowBean.getConditionerUseTime()*1000;
        }
        threeWaterInt= (int) flowBean.getStep5();
        dryInt= (int) flowBean.getStep6();
        if (flowBean.getStepTime()>0){
            stepInterval= (int) flowBean.getStepTime()*1000;
        }
        disinfectantInt= (int) flowBean.getStep7();
        windChangeInt= (int) flowBean.getStep8();
        fourWaterInt= (int) flowBean.getStep9();
        Log.e(TAG, "sendMsgToActivity: 实际沐浴露="+bodyWashInt1+";实际护毛素="+conditionerInt1+";间隔时间="+stepInterval );
        oneWaterInt=(oneWaterInt<=0)?10*1000:oneWaterInt*1000;
        bodyWashInt=(bodyWashInt<=0)?10*1000:bodyWashInt*1000;
        twoWaterInt=(twoWaterInt<=0)?10*1000:twoWaterInt*1000;
        conditionerInt=(conditionerInt<=0)?10*1000:conditionerInt*1000;
        threeWaterInt=(threeWaterInt<=0)?10*1000:threeWaterInt*1000;
        dryInt=(dryInt<=0)?10*1000:dryInt*1000;
        disinfectantInt=(disinfectantInt<=0)?10*1000:disinfectantInt*1000;
        windChangeInt=(windChangeInt<=0)?10*1000:windChangeInt*1000;
        fourWaterInt=(fourWaterInt<=0)?10*1000:fourWaterInt*1000;
        PreferenceUtil.commitInt(PreferenceUtil.FIRSTWATERTIME,oneWaterInt);
        PreferenceUtil.commitInt(PreferenceUtil.BODYWASHTIME,bodyWashInt);
        PreferenceUtil.commitInt(PreferenceUtil.BODYWASHUSE,bodyWashInt1);
        PreferenceUtil.commitInt(PreferenceUtil.SECONDWATERTIME,twoWaterInt);
        PreferenceUtil.commitInt(PreferenceUtil.CONDITIONERTIME,conditionerInt);
        PreferenceUtil.commitInt(PreferenceUtil.CONDITIONERUSE,conditionerInt1);
        PreferenceUtil.commitInt(PreferenceUtil.THIRDWATERTIME,threeWaterInt);
        PreferenceUtil.commitInt(PreferenceUtil.DRYTIME,dryInt);
        PreferenceUtil.commitInt(PreferenceUtil.DISINFECTANTTIME,disinfectantInt);
        PreferenceUtil.commitInt(PreferenceUtil.WINDINPUTTIME,windChangeInt);
        PreferenceUtil.commitInt(PreferenceUtil.FOURTHWATERTIME,fourWaterInt);
        PreferenceUtil.commitInt(PreferenceUtil.STEPINTERVAL,stepInterval);

    }

    private void handlerOtherConfig(DogOtherBean dogOtherBean){
        lowerWater=dogOtherBean.getLowTemp();
        upperWater=dogOtherBean.getStopHighTemp();
        if (dogOtherBean.getDownTemp()>0){
            houseLower=dogOtherBean.getDownTemp();
        }
        if (dogOtherBean.getUpTemp()>0){
            houseUpper=dogOtherBean.getUpTemp();
            if(houseUpper>=50){
                houseUpper=50;
            }
        }
        if(upperWater<=lowerWater){
            Log.e(TAG, "sendMsgToActivity: 水温限高限低出现了异常 高="+upperWater+";低="+lowerWater );
            return;
        }
        if (houseLower>=houseUpper){
            Log.e(TAG, "sendMsgToActivity: 环境温度限高限低出现了异常 高="+upperWater+";低="+lowerWater );
            return;
        }

        if(lowerWater<0){
            lowerWater=0;
        }
        if (upperWater>50){
            upperWater=50;
        }
        phoneNum=dogOtherBean.getAdminPhone();
        PreferenceUtil.commitString(PreferenceUtil.LOWTEM,""+lowerWater);
        PreferenceUtil.commitString(PreferenceUtil.HIGHTEM,""+upperWater);

        PreferenceUtil.commitString(PreferenceUtil.LOWINVIRTEM,""+houseLower);
        PreferenceUtil.commitString(PreferenceUtil.HIGHINVIRTEM,""+houseUpper);

        if (phoneNum!=null)
            PreferenceUtil.commitString(PreferenceUtil.BSIZEPHONE,phoneNum);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                deviceLinkTv.setText(phoneNum);
            }
        });
    }

    private void handlerFeaturesConfig(List<DogPriceBean> dogPriceBeanList){
        for (int i = 0; i < dogPriceBeanList.size(); i++) {
            if ("HIGHWASH".equals(dogPriceBeanList.get(i).getWashType())){
                //说明是高端精洗
                String uptime=dogPriceBeanList.get(i).getUpdateTime();
                double price=dogPriceBeanList.get(i).getPrice();
                if (price<=0){
                    price=0.01;
                }
                detailWashPrice=price;
//                PreferenceUtil.commitString(PreferenceUtil.DETAILDOGPRICETIME,uptime);
                PreferenceUtil.commitString(PreferenceUtil.DETAILWASHPRICE,""+price);
                List<DogPriceBean.PetTypeListDTO> petTypeListDTOList=dogPriceBeanList.get(i).getPetTypeList();
                for (int j = 0; j < petTypeListDTOList.size(); j++) {
                    if ("SMALL".equals(petTypeListDTOList.get(j).getPetType())){
                        double small=petTypeListDTOList.get(j).getMultiple();
                        small=(small<=0)?1:small;
                        smallDogPrice=small;
                        PreferenceUtil.commitString(PreferenceUtil.SMALLDOG,""+small);
                    }else if ("MIDDLE".equals(petTypeListDTOList.get(j).getPetType())){
                        double mid=petTypeListDTOList.get(j).getMultiple();
                        mid=(mid<=0)?1:mid;
                        midDogPrice=mid;
                        PreferenceUtil.commitString(PreferenceUtil.MIDDOG,""+mid);
                    }else if ("LARGE".equals(petTypeListDTOList.get(j).getPetType())){
                        double large=petTypeListDTOList.get(j).getMultiple();
                        large=(large<=0)?1:large;
                        bigDogPrice=large;
                        PreferenceUtil.commitString(PreferenceUtil.BIGDOG,""+large);
                    }else if ("SHORTHAIR".equals(petTypeListDTOList.get(j).getPetType())){
                        double shorthair=petTypeListDTOList.get(j).getMultiple();
                        shorthair=(shorthair<=0)?1:shorthair;
                        shortHairPrice=shorthair;
                        PreferenceUtil.commitString(PreferenceUtil.SHORTHAIR,""+shorthair);
                    }else if ("CURLYHAIR".equals(petTypeListDTOList.get(j).getPetType())){
                        double normalHair=petTypeListDTOList.get(j).getMultiple();
                        normalHair=(normalHair<=0)?1:normalHair;
                        normalLongHairPrice=normalHair;
                        PreferenceUtil.commitString(PreferenceUtil.NORMALLONGHAIR,""+normalHair);
                    }else if ("LONGHAIR".equals(petTypeListDTOList.get(j).getPetType())){
                        double longHair=petTypeListDTOList.get(j).getMultiple();
                        longHair=(longHair<=0)?1:longHair;
                        longHairPrice=longHair;
                        PreferenceUtil.commitString(PreferenceUtil.LONGHAIR,""+longHair);
                    }else if ("THIN".equals(petTypeListDTOList.get(j).getPetType())){
                        double thin=petTypeListDTOList.get(j).getMultiple();
                        thin=(thin<=0)?1:thin;
                        thinHairPrice=thin;
                        PreferenceUtil.commitString(PreferenceUtil.THINHAIR,""+thin);
                    }else if ("NORMAL".equals(petTypeListDTOList.get(j).getPetType())){
                        double tickfea=petTypeListDTOList.get(j).getMultiple();
                        tickfea=(tickfea<=0)?1:tickfea;
                        normalHairPrice=tickfea;
                        PreferenceUtil.commitString(PreferenceUtil.NORMALHAIR,""+tickfea);
                    }else if ("THICK".equals(petTypeListDTOList.get(j).getPetType())){
                        double thick=petTypeListDTOList.get(j).getMultiple();
                        thick=(thick<=0)?1:thick;
                        thickHairPrice=thick;
                        PreferenceUtil.commitString(PreferenceUtil.THICKHAIR,""+thick);
                    }else if ("DRY".equals(petTypeListDTOList.get(j).getPetType())){
                        double dry=petTypeListDTOList.get(j).getMultiple();
                        dry=(dry<=0)?1:dry;
                        dryDogPrice=dry;
                        PreferenceUtil.commitString(PreferenceUtil.DRYDOG,""+dry);
                    }else if ("WASHDRY".equals(petTypeListDTOList.get(j).getPetType())){
                        double washdry=petTypeListDTOList.get(j).getMultiple();
                        washdry=(washdry<=0)?1:washdry;
                        washDryPrice=washdry;
                        PreferenceUtil.commitString(PreferenceUtil.WASHDRYDOG,""+washdry);
                    }


                }
            } else if ("QUICKWASH".equals(dogPriceBeanList.get(i).getWashType())){
                //说明是一键洗狗
                String uptime=dogPriceBeanList.get(i).getUpdateTime();
                double price=dogPriceBeanList.get(i).getPrice();
                if (price<=0){
                    price=0.01;
                }
                oneKeyWashPrice=price;
//                PreferenceUtil.commitString(PreferenceUtil.ONEDOGPRICETIME,uptime);
                PreferenceUtil.commitString(PreferenceUtil.ONEWASHPRICE, ""+price);

            }
        }

    }

    /**
     * 从服务那返回的数据处理
     * @param key
     * @param value
     */
    @Override
    public void sendMsgToActivity(String key, Object value) {

        switch (key){
            case ActivityConfig.sclive: {
                //直播广告,在这里进行列表检查。
                // 1.看是否有当前时间段的，如果有则开启直播；如果没有则不开启。
                // 2.开始保存列表到数据库
                // 3.进行列表定时启动

                try {
//                    JSONObject object=new JSONObject(((String) value));
//                    String orderTime=object.optString("currentTime");
//                    String liveStr=object.optString("configMains");
//                    List<ReceiveLiveSubBean> liveList=new Gson().fromJson(liveStr,new TypeToken<List<ReceiveLiveSubBean>>(){}.getType());

                    LiveObjBean<List<LiveContentBean>> liveObjBean = (LiveObjBean<List<LiveContentBean>>) value;
                    String orderTime = liveObjBean.getCurrentTime();
                    List<LiveContentBean> liveList = liveObjBean.getConfigMains();

                    Log.i(TAG, "sendMsgToActivity: 直播指令下发时间=" + orderTime);

                    //清除定时列表
                    int lastLiveSize = PreferenceUtil.getInt(PreferenceUtil.ALARMLIVESIZE, 0);
                    Log.i(TAG, "直播检查上一次的定时列表，取消闹钟:" + lastLiveSize);
                    if (lastLiveSize > 0) {
                        //500这个段是记录直播列表的
                        for (int j = 0; j < lastLiveSize; j++) {
                            int lastStartInt = PreferenceUtil.getInt("alarm" + (j * 2 + 501), -1);
                            int lastEndInt = PreferenceUtil.getInt("alarm" + (j * 2 + 502), -1);
                            AlarmUtil.cancelAlarm(lastStartInt, lastEndInt,DogActivity.this);   //取消闹钟
                        }

                    }
                    //清空数据库表格
                    if (sqliteManager != null) {
                        sqliteManager.clearLiveTable();
                    }
                    PreferenceUtil.commitInt(PreferenceUtil.ALARMLIVESIZE, liveList.size());

                    isLiveFlag = false;//先设置为false，保证音视频的可用。如果在时间段内，则会为true
                    boolean noLive = false;
                    //检查当前有没有播放的时间段
                    if (liveList != null && liveList.size() > 0) {
                        boolean currentLiveFlag = false;
                        PreferenceUtil.commitBoolean(PreferenceUtil.LIVEFLAG, true);
                        Log.i(TAG, "直播 这一个闹钟列表长度为:" + liveList.size());
                        for (int j = 0; j < liveList.size(); j++) {
                            String startStr = liveList.get(j).getStartTime();
                            String endStr = liveList.get(j).getEndTime();
                            String url = liveList.get(j).getUrl();
                            Integer volumeInteger = liveList.get(j).getVolume();
                            int volume = 15;
                            if (volumeInteger != null) {
                                volume = volumeInteger.intValue();
                            }

                            Log.i(TAG, "sendMsgToActivity直播的时间: " + startStr + "；直播的声音=" + volumeInteger);
                            //进行时间定时

                            Calendar startCalendar = AlarmUtil.getCaledar(startStr, 0);
                            AlarmUtil.startAlarm(DogActivity.this, startCalendar, j * 2 + 501);
                            PreferenceUtil.commitInt("alarm" + (j * 2 + 501), j * 2 + 501);
                            Calendar endCalendar = AlarmUtil.getCaledar(endStr, 0);
                            AlarmUtil.startAlarm(DogActivity.this, endCalendar, j * 2 + 502);
                            PreferenceUtil.commitInt("alarm" + (j * 2 + 502), j * 2 + 502);

                            //保存到数据库
//                            ContentValues contentValues=new ContentValues();
                            contentValues.clear();
                            contentValues.put("liveContent", url);
                            contentValues.put("startTime", startStr);
                            contentValues.put("endTime", endStr);
                            contentValues.put("alarm1", (j * 2 + 501));
                            contentValues.put("alarm2", (j * 2 + 502));
                            contentValues.put("dotime", orderTime);
                            contentValues.put("volume", volume);
                            sqliteManager.saveLiveItem(contentValues);


                            long startLo = AlarmUtil.getCurrentCaledar(startStr, 0).getTimeInMillis();
                            long endLo = AlarmUtil.getCurrentCaledar(endStr, 0).getTimeInMillis();
                            long orderLo = System.currentTimeMillis();
                            //                      这种情况是跨天的时候                                                  这种是当天
                            if ((startLo > endLo && orderLo > startLo && orderLo < endCalendar.getTimeInMillis()) || (orderLo > startLo && orderLo < endLo)) {
                                currentLiveFlag = true;

                                isLiveFlag = true;
                                isInFreeAdFlag=false;
                                Log.i(TAG, "receiveWork: 直播的标志333=" + isLiveFlag);
                                isAdvertisement = false;

                                if (url.length()<=4 || (url.length()>4 && !("http".equals(url.substring(0,4)) || "rtmp".equals(url.substring(0,4))))){
                                    Log.i(TAG, "sendMsgToActivity: 直播的标志 出现url问题="+url.length()+";url="+url);
                                    currentLiveFlag=false;
                                    isInFreeAdFlag=true;
                                    isLiveFlag=false;
                                }else{

                                    //如果有播放时间段，那么开始播放
                                    if (url != null) {

                                        musicVolumn = volume;
                                        if (isVolumeOn) {
                                            audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, fixedVolume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
                                        } else {
                                            audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
                                        }

                                        Message message=handler.obtainMessage();
                                        message.obj=url;
                                        message.what=LIVEAD;
                                        handler.sendMessage(message);

                                    }
                                }




                            }
                        }

                        if (!currentLiveFlag) {
                            //如果当前没有播报时段
                            noLive = true;

                        }
                    } else {
                        PreferenceUtil.commitBoolean(PreferenceUtil.LIVEFLAG, false);
                        noLive = true;
                    }

                    Log.i(TAG, "sendMsgToActivity: 收到直播信息=" + noLive + ";" + isAdvertisement + ";" + isLiveFlag +";是否正在播放="+mPlayer.isPlaying());
                    if (noLive) {    //首先判断是没有处于直播列表之内
                        if (!isAdvertisement || isLiveFlag) {    //再判断当前没有处于广告播放之中，或者是处于直播之中。都需要重新获取一次列表
                            //                        PreferenceUtil.commitBoolean(PreferenceUtil.LIVEFLAG,false);
                            isLiveFlag = false;
                            fromLiveFlag = true;
                            isPlay = true;
                            if (mPlayer != null) {
                                mPlayer.stop();
                                mPlayer.reset();
                            }
                            cacheLinkedDeque1.add("008");
                            synchronized (receiveObject) {
                                receiveObject.notifyAll();
                            }

                        }
                    }
                } catch (Exception e) {
                    Log.i(TAG, "sendMsgToActivity: 直播异常000=" + e.getLocalizedMessage());
                    e.printStackTrace();
                }

                break;
            }
            // 普通广告进行数据同步
            case ActivityConfig.syncadvert: {

                List<AlarmBean> alarmBeanList = (List<AlarmBean>) value;


                speakWarning(getString(R.string.setav));

                Log.i(TAG, "sendMsgToActivity:收到 进入了新的解码方式"  + ";" + isLiveFlag );

                //取消当前闹钟，开始这个列表的闹钟
                isNullFlag = false;
                boolean isOnPlay = false;//这个是广告播放的标志，是为了解除当前在播放上一个列表，
                // 但是我把时间段把当前播放的时间段设置为空闲广告的时候

                try {
                    //获取上一次闹钟列表的数量
                    int lastAlarmSize = PreferenceUtil.getInt(PreferenceUtil.ALARMSIZE, 0);
                    //先关掉全部闹钟
                    for (int i = 0; i < lastAlarmSize; i++) {

                        int lastStartInt = PreferenceUtil.getInt("alarm" + (i * 2 + 1), -1);
                        int lastEndInt = PreferenceUtil.getInt("alarm" + (i * 2 + 2), -1);
                        if (lastStartInt == -1) {
                            //闹钟没有设置过
                        } else {
                            //已经设置过，那么需要将之前设置的闹钟，关掉
                            Intent intent1 = new Intent(DogActivity.this, AlarmReciever.class);
                            intent1.putExtra("_id", lastStartInt);
                            PendingIntent pendingIntent = PendingIntent.getBroadcast(DogActivity.this, lastStartInt, intent1, 0);

                            AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
                            alarmManager.cancel(pendingIntent);
                        }

                        if (lastEndInt == -1) {
                            //闹钟没有设置过
                        } else {
                            //已经设置过，那么需要将之前设置的闹钟，关掉

                            AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);


                            Intent intent2 = new Intent(DogActivity.this, AlarmReciever.class);
                            intent2.putExtra("_id", lastEndInt);
                            PendingIntent pendingIntent = PendingIntent.getBroadcast(DogActivity.this, lastEndInt, intent2, 0);
                            alarmManager.cancel(pendingIntent);

                        }

                    }

                    //直接清空整张表格
                    sqliteManager.clearTable();
                    PreferenceUtil.commitInt(PreferenceUtil.ALARMSIZE, alarmBeanList.size());

                    boolean terminalDoOne = true;

                    //开始设置闹钟
                    for (int i = 0; i < alarmBeanList.size(); i++) {

                        //说明是有的闹钟
                        int alarmId = alarmBeanList.get(i).getId();//获取到闹钟的id
                        String startadTime = alarmBeanList.get(i).getStartTime();//获取到闹钟开始的时间
                        String endTime = alarmBeanList.get(i).getEndTime();//获取到闹钟关闭时间
                        int volumn = alarmBeanList.get(i).getVolume();
                        String avTime1 = alarmBeanList.get(i).getTotalDuration();
                        String orderTime = alarmBeanList.get(i).getCurrentTime();
                        String terminal = alarmBeanList.get(i).getIsActive();//是否为终端主动请求，如果是，则为1，如果不是则为0
                        int alarmMode = alarmBeanList.get(i).getPlayMode();//播放模式
                        int playTimes = alarmBeanList.get(i).getTimes();//播放次数
                        List<AlarmPlayBean> downloadBeans = alarmBeanList.get(i).getList();

                        //处理列表里面没有播放列表的情况
                        if (downloadBeans.size() == 0) {
                            continue;
                        }

                        AlarmUtil.alarmPlayer(DogActivity.this,startadTime,1,(i * 2 + 1));
                        AlarmUtil.alarmPlayer(DogActivity.this,endTime,0,(i * 2 + 2));

                        String startEnd = startadTime + "," + endTime;
                        //设置了之后，保存一下
                        PreferenceUtil.commitInt("alarm" + (i * 2 + 1), i * 2 + 1);
                        PreferenceUtil.commitInt("alarm" + (i * 2 + 2), i * 2 + 2);
                        PreferenceUtil.commitString("alarmTime" + i, startEnd);
//                        Log.i(TAG, "receiveWork: 提交开始闹钟"+(i*2+1));
//                        Log.i(TAG, "receiveWork: 提交结束闹钟"+(i*2+2));
//                        Log.i(TAG, "receiveWork: 提交闹钟列表"+i+";"+startEnd);


                        //批量添加闹钟数据
//                        sqliteManager.getMdb().beginTransaction();
                        //下面将闹钟alarmId和要播放的文件写入数据库。是否可以将i变成闹钟id，这个是唯一性
                        for (int j = 0; j < downloadBeans.size(); j++) {
                            // 1.先检查是否下载，如果没下载或者数据库没有这个，则去下载。如果下载了，更新数据库播放
                            String md5 = downloadBeans.get(j).getMd5();       //md5
                            int type = downloadBeans.get(j).getType();        //播放类型
                            String ext = downloadBeans.get(j).getExt();       //后缀名
                            String total = downloadBeans.get(j).getSize() + ""; //总长度
                            int downloadId = downloadBeans.get(j).getConfId();//下载id
                            int alarmIds = downloadBeans.get(j).getAdvertId();//闹钟id
                            int duration = downloadBeans.get(j).getDuration();//播放时间
                            int playIndex = downloadBeans.get(j).getSeq();    //播放排序
                            String content = downloadBeans.get(j).getContent();//播放文字
                            String playName=downloadBeans.get(j).getName();     //获取真正的名字

                            Log.i(TAG, "receiveWork=: " + md5 + ":" + type + ":" + ext + ":" + total + ":" + downloadId);

                            if (md5 != null) {
                                if (type == 4 || type == 5) {

                                } else {

                                    File file = null;
                                    if (sdPath == null || sdPath.length() == 0) {
                                        file = new File(TestConfig.downloadFilePath + md5 + "." + ext);
                                    } else {
                                        file = new File(sdPath + "/solar/download/" + md5 + "." + ext);
                                    }
//                                    Log.i(TAG, "receiveWork=: "+TestConfig.downloadFilePath+md5+"."+ext);
//                                    Log.i(TAG, "receiveWork=: "+sdPath+"/solar/download/"+md5+"."+ext);
                                    //这里是判断存储之前就有文件的时候
                                    if (file.length() == Long.valueOf(total)) {
                                        Log.i(TAG, "receiveWork=: 文件已经下载下来了" + md5);

                                    } else {
                                        DownloadItem downloadItem = sqliteManager.downloadIdCheck(md5);

//                                Log.i(TAG, "receiveWork: "+downloadItem.getDownloadExt() );
//                                Log.i(TAG, "receiveWork: "+downloadItem.getPlayType() );
//                                Log.i(TAG, "receiveWork: "+downloadItem.getDownloadId() );
//                                Log.i(TAG, "receiveWork: "+downloadItem.getDownloadFlag() );
//                                Log.i(TAG, "receiveWork: "+downloadItem.getDownloadLength() );
//                                Log.i(TAG, "receiveWork: "+downloadItem.getDownloadName() );
//                                Log.i(TAG, "receiveWork: "+downloadItem.getDownloadTotal() );

                                        //主要查询
                                        if (downloadItem.getDownloadMd5() != null) {
                                            //如果没有下载，则
//                                        if(downloadItem.getDownloadFlag()==2){
//                                            //已下载
//                                        }else {
//                                            //未下载或者未完,则去下载
//                                            Log.i(TAG, "receiveWork:md5 "+downloadItem.getDownloadMd5() );
//                                            if (downloadItem.getDownloadMd5()!=null){
////                                                setUploadFile(downloadItem.getDownloadMd5());
//                                                Message message1=handler.obtainMessage();
//                                                Log.i(TAG, "threadPoolUploadFile: 七牛云==下载77" );
//                                                message1.what=DOWNLOADQINIU;
//                                                message1.obj=downloadItem.getDownloadMd5();
//                                                handler.sendMessage(message1);
//                                            }
//
//                                        }
                                        } else {
                                            //如果没有，添加一条
//                                        ContentValues contentValues=new ContentValues();
                                            contentValues.clear();
                                            contentValues.put("downloadMd5", md5);
                                            contentValues.put("downloadLength", "0");
                                            contentValues.put("downloadName", md5 + "." + ext);
                                            contentValues.put("downloadFlag", 1);
                                            contentValues.put("downloadTotal", total);
                                            contentValues.put("downloadId", downloadId);
                                            contentValues.put("playType", type);
                                            contentValues.put("downloadExt", ext);
                                            sqliteManager.addDownLoadItem(contentValues);

                                            //再去下载
//                                        setUploadFile(md5);
//                                        Message message1=handler.obtainMessage();
//                                        Log.i(TAG, "threadPoolUploadFile: 七牛云==下载88" );
//                                        message1.what=DOWNLOADQINIU;
//                                        message1.obj=md5;
//                                        handler.sendMessage(message1);
                                        }
                                    }

                                }


                                //播放列表直接添加
//                                ContentValues contentValues=new ContentValues();
                                contentValues.clear();
                                contentValues.put("content", content);
                                contentValues.put("downloadMd5", md5);
                                contentValues.put("playExt", ext);
                                contentValues.put("playName", md5 + "." + ext);
                                contentValues.put("playType", type);
                                contentValues.put("downloadTotal", total);
                                contentValues.put("downloadId", downloadId);
                                contentValues.put("playTime", duration);
                                contentValues.put("alarmId", alarmId);
                                contentValues.put("playIndex", playIndex);
                                contentValues.put("alarm1", (i * 2 + 1));
//                                Log.i(TAG, "receiveWork: 直接刷新数据这个alarm1为："+(i*2+1) );
                                contentValues.put("alarm2", (i * 2 + 2));
                                contentValues.put("startTime", startadTime);
                                contentValues.put("endTime", endTime);
                                contentValues.put("volumn", volumn);
                                contentValues.put("avTime", avTime1);
                                contentValues.put("mediaName",playName);
                                sqliteManager.addPlayItem(contentValues);

                            }
                        }

                        Log.i(TAG, "receiveWork: 同步请求方式" + terminal + ";" + terminalDoOne);
                        if ("1".equals(terminal) && terminalDoOne) {
                            terminalDoOne = false;

                        }



                        if (isLiveFlag) {
//                            Log.i(TAG, "receiveWork: 广告直接刷新数据==");
                            isOnPlay = true;
                            continue;
                        }


//                        Log.i(TAG, "receiveWork: 广告直接刷新数据"+(i*2+1) );
                        int start = Integer.valueOf(startadTime.split(":")[0]) * 60 + Integer.valueOf(startadTime.split(":")[1]);
                        int end = Integer.valueOf(endTime.split(":")[0]) * 60 + Integer.valueOf(endTime.split(":")[1]);
//                        Log.i(TAG, "receiveWork: 广告直接刷新数据:startTime:"+startTime );
//                        Log.i(TAG, "receiveWork: 广告直接刷新数据:endTime:"+endTime );
//                        Log.i(TAG, "receiveWork: 广告直接刷新数据:start:"+start );
//                        Log.i(TAG, "receiveWork: 广告直接刷新数据:end:"+end );

                        //直接比较时间戳比较好 直接刷新
                        Date date = new Date();
                        int now = date.getHours() * 60 + date.getMinutes();
//                        Log.i(TAG, "receiveWork: 直接刷新数据:now:"+now );
                        if (now >= start && now < end) {
                            isOnPlay = true;
                            String alarmStr = (i * 2 + 1) + "";
//                            Log.i(TAG, "receiveWork: 直接刷新数据，只有一个开始的:"+alarmStr );
                            ArrayList<PlayItem> playItems1 = sqliteManager.playCheckSingleUrl(alarmStr);
//                            Log.i(TAG, "receiveWork:直接刷新数据 "+playItems1.get(0).getPlayName() );
                            if (playItems1.size() != 0 && playItems1.size() >= 1) {

//                                //这个是关闭指令
                                if (mPlayer != null && mPlayer.isPlaying()) {
                                    Log.i(TAG, "sendMsgToActivity: 先停掉之前的播放内容11111111111" );
                                    mPlayer.stop();
                                    mPlayer.reset();
                                }
                                isPlay = true;
                                isplayIn = false;
                                playInt = -1;
                                Message message1=handler.obtainMessage();
                                message1.what=WARNSHOW;
                                message1.arg1=2;
                                handler.sendMessage(message1);


//                    Log.i(TAG, "Event: 关闭指令" );
                                playItems = null;

                                Thread.sleep(200);

                                playItems = playItems1;
                                playItemBackpackages = playItems1;

                                //开始确认音量值
                                musicVolumn = playItems.get(0).getVolumn();
                                Log.i(TAG, "receiveWork: 从后台返回 开机广告 时的音量" + musicVolumn + ";vv=" + vv.isPlaying() + ";ttp=" + textToSpeech.isSpeaking());

                                if (!vv.isPlaying() && !textToSpeech.isSpeaking()) {
                                    if (isVolumeOn) {
                                        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, fixedVolume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
                                    } else {
                                        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, musicVolumn, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
                                    }

                                    Log.i(TAG, "receiveWork: 0000从后台返回 开机广告 时的音量" + musicVolumn);
                                } else {
                                    currentVolumn = musicVolumn;
                                    Log.i(TAG, "receiveWork: 1111从后台返回 开机广告 时的音量,声音=" + musicVolumn);
                                }
//                                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,musicVolumn,AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);

                                if (isVolumeOn) {
                                    audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, fixedVolume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
                                } else {
                                    audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, musicVolumn, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
                                }

                                isplayIn = true;
                                playInt = 0;

                                isAdvertisement = true;
                                if (!isLiveFlag) {
                                    playMediaFile();
                                }


                            }

                        }

                    }

                    //如果没有播放时间段，而且
                    if (!isOnPlay) {
                        isPlayOn = false;
                        currentVolumn = 1;//关闭后设置当前音量值，避免出现这个情况：
                        Log.i(TAG, "receiveWork: 2222从后台返回 开机广告 时的音量，声音=" + currentVolumn + ";" + musicVolumn);

                        // 广播播放前是广告，它是按照广告的音量设置，但是当广播播放完之后，
                        // 广告刚刚好在它之前播放完。这样子就会造成闲时广告会使用广告的音量

                        alarmId = -1;

                        PreferenceUtil.commitString("currentNoise", "no");
//                            //这个是关闭指令
//                            if (mPlayer!=null && mPlayer.isPlaying()){
//                                mPlayer.stop();
//                                mPlayer.reset();
//                            }
                        isPlay = true;
                        isplayIn = false;
                        playInt = -1;

//                    Log.i(TAG, "Event: 关闭指令" );
                        playItems = null;
                        isAdvertisement=false;
                        if (!isLiveFlag) {
                            //开机设置闲时音量
                            if (!vv.isPlaying() && !textToSpeech.isSpeaking()) {
                                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, freeVolumn, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
                            } else {
                                currentVolumn = freeVolumn;
                                Log.i(TAG, "receiveWork: 3333从后台返回 开机广告 时的音量,声音值=" + currentVolumn);
                            }
                            playMediaFile();
                        }

                    } else {
                        isPlayOn = true;
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }

                break;
            }
            case ActivityConfig.advertdownload: {
                //获取文件下载信息的
                String receiveMsg= (String) value;
                cacheLinkedDeque1.add("005" + receiveMsg);
                synchronized (receiveObject) {
                    receiveObject.notifyAll();
                }
                break;
            }
            case ActivityConfig.partcode: {
                Log.i(TAG, "sendMsgToActivity: 从服务端获取" + value);
                decideActivity(((String) value));
                break;
            }
            case ActivityConfig.cr: {

                //推流
                if (cameraFragment != null) {
                    //重新打开摄像头
                    Log.i(TAG, "receiveWork: 从cr直接进入摄像头界面打开摄像头" + publishStr);
                    if (SocketService.isQiNiuFlag) {
                        if (publishStr != null) {
                            cameraFragment.startRtmpPublisher(false, publishStr);
                        } else {
                            publishStr = QiNiuUtil.getRtmpUrl(isQiniuFlag, TestConfig.accessKey, TestConfig.secretKey,DogActivity.this);
                            if (cameraFragment != null && publishStr!=null) {
                                cameraFragment.startRtmpPublisher(false, publishStr);
                            }
                        }
                    } else {
                        cameraFragment.startRtmpPublisher(false);
                    }

                }
                break;
            }
            case ActivityConfig.ct: {
                //断开推流
                if (cameraFragment != null) {
                    //重新打开摄像头
                    Log.i(TAG, "receiveWork: 停止摄像头播放");
                    if (SocketService.isQiNiuFlag) {
                        if (publishStr != null) {
                            cameraFragment.stopRtmpPublisher(publishStr);
                        }
                    } else {
                        cameraFragment.stopRtmpPublish();
                    }

                }
                break;
            }
            case "zoomtele": {
                if (cameraFragment != null) {
                    cameraFragment.setCameraOperation("zoomtele", TestConfig.itfi, TestConfig.usrname, TestConfig.pwd, ip);

                }
                break;
            }
            case "zoomwide": {
                if (cameraFragment != null) {
                    cameraFragment.setCameraOperation("zoomwide", TestConfig.itfi, TestConfig.usrname, TestConfig.pwd, ip);
                }

                //缩小

                break;
            }
            case "up": {

                if (cameraFragment != null) {
                    cameraFragment.setCameraOperation("up", TestConfig.itfi, TestConfig.usrname, TestConfig.pwd, ip);
                }

                //向上

                break;
            }
            case "down": {

                if (cameraFragment != null) {
                    cameraFragment.setCameraOperation("down", TestConfig.itfi, TestConfig.usrname, TestConfig.pwd, ip);
                }

                //向下


                break;
            }
            case "right": {
                Log.i(TAG, "sendMsgToActivity摄像头操作000: right" );
                if (cameraFragment != null) {
                    Log.i(TAG, "sendMsgToActivity摄像头操作111: " );
                    cameraFragment.setCameraOperation("right", TestConfig.itfi, TestConfig.usrname, TestConfig.pwd, ip);
                }


                //向右

                break;
            }
            case "left": {

                if (cameraFragment != null) {
                    cameraFragment.setCameraOperation("left", TestConfig.itfi, TestConfig.usrname, TestConfig.pwd, ip);
                }

                //向左

                break;
            }
            case "stop": {

                if (cameraFragment != null) {
                    cameraFragment.setCameraOperation("stop", TestConfig.itfi, TestConfig.usrname, TestConfig.pwd, ip);
                }

                //停止

                break;
            }
            case ActivityConfig.PAYSUCCESS:{
                //支付成功后的订单
                PaySuccessBean paySuccessBean= (PaySuccessBean) value;
                order_No=paySuccessBean.getOrder_no();
                order_amount=paySuccessBean.getOrder_amount();
                order_state=paySuccessBean.getTrade_status();
                trade_no=paySuccessBean.getTrade_no();
                if (("SUCCESS").equals(order_state)){
                    //说明已经支付成功 开始进入洗狗第一状态  发送开门指令
                    Log.e(TAG, "sendMsgToActivity: 如果门未打开，让客户拉开门再把狗放进去");
                    touchSwitchFlag=false;
                    stage=1;
                    sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXOPENDOOR);//开门
                }
                sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXLIGHTOPEN);//内照明打开
                Log.e(TAG, "sendMsgToActivity: 显示支付成功指令");
                handler.sendEmptyMessage(DOGPAYSUCCESS);//显示
                setFlowMsg("支付成功，洗宠准备中。。。",0);

                break;
            }
            case ActivityConfig.SHOWBACK:{

                String receive= (String) value;
                String backOrder=receive.substring(0,12);
                //这些都是发送指令返回的
                if (("0106000300AA").equals(backOrder)){
                    //说明是打开加热返回的
                    Log.e(TAG, "sendMsgToActivity: 加热打开返回的指令为" );
                    heatingWaterIsOpenFlag=true;
                }else if (("0106000300BB").equals(backOrder)){
                    //说明是关闭加热返回的
                    Log.e(TAG, "sendMsgToActivity: 加热关闭返回的指令为" );
                    heatingWaterIsOpenFlag=false;
                }else if (("0106000A00AA").equals(backOrder)){
                    //说明是打开烘干加热条返回的
                    Log.e(TAG, "sendMsgToActivity: 加热条打开返回的指令为" );
                    heatingInvirIsOpenFlag=true;
                }else if (("0106000A00BB").equals(backOrder)){
                    //说明是关闭烘干加热条返回的
                    Log.e(TAG, "sendMsgToActivity: 加热关闭返回的指令为" );
                    heatingInvirIsOpenFlag=false;
                }else if (("0106000100A1").equals(backOrder)){
                    //开门成功指令返回  是否也做成差异化，这样子返回不同的参数表明在不同时段打开狗门   例如 0106000100AA00是流程一打开，0106000100AA01是流程九打开，0106000100AA02是流程十打开
                    Log.e(TAG, "sendMsgToActivity: 狗门打开返回的指令为" );
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            speakDogStateWarn("请把门拉开，把您的爱宠放进来");
                        }
                    });

                    //马上发一条指令，检查接触开关状态  主要避免出现5s的情况
                    sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXSTATUS2);
                    touchSwitchFlag=false;

                }else if (("0106000100B1").equals(backOrder)){
                    //关门成功指令返回  是否也做成差异化，这样子返回不同的参数表明在不同时段打开狗门   例如 0106000100AA00是流程一打开，0106000100AA01是流程九打开，0106000100AA02是流程十打开
                    Log.e(TAG, "sendMsgToActivity: 狗门关闭返回的指令为" );
                    //门已经关闭，即将开始进行洗狗工作
                    speakDogStateWarn("门已经锁好，马上进行清洗工作！");
                    handler.sendEmptyMessage(DOGCLOSEDOORDISMISSSHOW);
                    //打开内照明
                    sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXLIGHTOPEN);
                    //进入 流程二
                    stage=2;
                    sendFlowNum(3);

                }else if(("0106000100A2").equals(backOrder)){
                    //在这里进行加热丝关闭
                    sendMechineOrders(SerialConfigUtil.CONFIGDOGBOXHEATINGCLOSE);
                    // 开门成功指令返回， 这个是洗狗完成后
                    Log.e(TAG, "sendMsgToActivity: 已经洗狗完成，开门放狗" );
                    setOpenDoorWarn("您的爱宠已经洗好了，请开门放它出来");
                    stage=9;
                    touchSwitchFlag=false;
                    speakDogStateWarn("您的爱宠已经洗好了，请开门带它离开");
                }else if (("0106000100B2").equals(backOrder)){
                    //关门成功指令返回  是否也做成差异化，这样子返回不同的参数表明在不同时段打开狗门   例如 0106000100AA00是流程一打开，0106000100AA01是流程九打开，0106000100AA02是流程十打开
                    disinfection();

                }else if (("0106000100AA").equals(backOrder)){
                    //异常开门，或许还有其他需要注意事项
                    setOpenDoorWarn("门锁已经打开，请带走您的爱宠");
                    stage=100;
                    touchSwitchFlag=false;
                    speakDogStateWarn("门锁已打开，请开门带走您的爱宠");
                }else if (("0106000100BB".equals(backOrder))){
                    Log.e(TAG, "sendMsgToActivity: 门锁已经关好" );
                    handler.sendEmptyMessage(DOGCLOSEDOORDISMISSSHOW);
                }
                break;
            }
            case ActivityConfig.DOGBOXSTATEINFOFLAG:{
                if (stage>0 && stage<3){
                    //说明在付款后，还未洗狗阶段
                    //计算洗狗时间和进入洗狗状态
                    dogboxState=1;
                    leaveTime=(int) ((totalMul*(oneWaterInt+bodyWashInt+twoWaterInt+conditionerInt+threeWaterInt+dryInt)+disinfectantInt+windChangeInt+fourWaterInt+preheatInt)/1000/60);
                }else if (stage>=3 && stage<9){
                    //说明在洗狗中
                    dogboxState=1;
                    if (stage==3){
                        leaveTime=(int) ((totalMul*(bodyWashInt+twoWaterInt+conditionerInt+threeWaterInt+dryInt)+disinfectantInt+windChangeInt+fourWaterInt+preheatInt+flowLeaveTime)/1000/60);
                    }else if (stage==4){
                        leaveTime=(int) ((totalMul*(twoWaterInt+conditionerInt+threeWaterInt+dryInt)+disinfectantInt+windChangeInt+fourWaterInt+preheatInt+flowLeaveTime)/1000/60);
                    }else if (stage==5){
                        leaveTime=(int) ((totalMul*(conditionerInt+threeWaterInt+dryInt)+disinfectantInt+windChangeInt+fourWaterInt+preheatInt+flowLeaveTime)/1000/60);
                    }else if (stage==6){
                        leaveTime=(int) ((totalMul*(threeWaterInt+dryInt)+disinfectantInt+windChangeInt+fourWaterInt+preheatInt+flowLeaveTime)/1000/60);
                    }else if (stage==7){
                        leaveTime=(int) ((totalMul*(dryInt)+disinfectantInt+windChangeInt+fourWaterInt+preheatInt+flowLeaveTime)/1000/60);
                    }else if (stage==8){
                        leaveTime=(int) ((disinfectantInt+windChangeInt+fourWaterInt+preheatInt+flowLeaveTime)/1000/60);
                    }
                }else if(stage>=9 && stage<14){
                    //消毒状态
                    dogboxState=2;
                    leaveTime=(int) ((disinfectantInt+windChangeInt+fourWaterInt+preheatInt+flowLeaveTime)/1000/60);
                }else{
                    //空闲中
                    dogboxState=0;
                    leaveTime=0;
                }
                Log.e(TAG, "sendMsgToActivity: 洗狗机状态 洗狗时间 stage="+stage);
                Log.e(TAG, "sendMsgToActivity: 洗狗机状态 洗狗时间--oneWaterInt="+oneWaterInt+";bodyWashInt="+bodyWashInt+";twoWaterInt="+twoWaterInt+";conditionerInt="+conditionerInt+";threeWaterInt="+threeWaterInt+";dryInt="+dryInt );
                Log.e(TAG, "sendMsgToActivity: 洗狗机状态 消毒时间--disinfectantInt="+disinfectantInt+";windChangeInt="+windChangeInt+";fourWaterInt="+fourWaterInt+";preheatInt="+preheatInt+";flowLeaveTime="+flowLeaveTime );
                setDogboxState();
                break;
            }
            case ActivityConfig.nt:{
                String version= (String) value;
                if (version!=null && version.length()>0){
                    String[] codeStr=version.split("\\.");
                    Log.i(TAG, "sendMsgToActivity:== "+codeStr.length );
                    int code=0;
                    for (int i = 0; i < codeStr.length; i++) {
                        Log.i(TAG, "sendMsgToActivity:== "+codeStr[codeStr.length-1-i] +";数字="+Math.pow(10,i*2));
                        code=code+(int)(Integer.valueOf(codeStr[codeStr.length-1-i])*Math.pow(10,i*2));
                    }
                    Log.i(TAG, "sendMsgToActivity: 要升级的版本号为="+code +";机身本身版本号="+appVersionCodeInt);

                    if (code>appVersionCodeInt){
                        //只有大于，才进行升级
                        if (pversion != null && (!pversion.equals(version))) {
                            PreferenceUtil.commitInt(PreferenceUtil.LENGTH, 0);
                        }
                        //主动升级到某一个版本
                        pversion = version;
                        PreferenceUtil.commitString(PreferenceUtil.UPVERSION, pversion);
                        Log.i(TAG, "onReceive 升级的版本是: " + pversion);
                        getVerParams().clear();
                        verParams=VersionUtil.startToUpdate(pversion,DogActivity.this);
                        if (verParams!=null){
                            handler.sendEmptyMessage(VERSIONKEY);
                        }
                    }else{
                        //是否主动进行固件升级？

                    }



                }


                break;
            }
            case ActivityConfig.upapk:{
                //手动升级apk
                String cmd= (String) value;
                FlyUtil.initInot(DogActivity.this).execSuCmd(cmd);
                Log.i(TAG, "sendMsgToActivity: 已经执行了升级指令");
                break;
            }
            case ActivityConfig.DOGCANCELPOP:{
                if (warnDialog!=null){
                    warnDialog.dismissUrgenDialog();
                    warnDialog.dismissDisinfectantsDialog();
                    warnDialog.dismissOpenDoorDialog();
                    warnDialog.dismissCloseDoorDialog();
                }
                break;
            }
            case ActivityConfig.DOGBOXWORKTIME:{
                //进行定时工作数据解析

                break;
            }

        }
    }

    private synchronized void disinfection(){
        if (stage==9){
            Log.e(TAG, "sendMsgToActivity: 洗狗完成，开始消毒" );
            handler.sendEmptyMessage(DOGCLOSEDOORDISMISSSHOW);
            //门已经关闭，即将开始进行洗狗工作
            speakDogStateWarn("门已经锁好，马上进行消毒工作！");
            handler.sendEmptyMessage(DISINFECTANTSSHOW);
//                    setDoorWarn("消毒中。。。");
            //进入 流程十
            stage=10;
            startToDisinfection();
        }
    }

    private void setDogboxState(){
        if (mSocketService!=null){
            mSocketService.setDogStatus(dogboxState,leaveTime);
        }
    }

    private void setCloseDoorWarn(String content){
        Message dogMsg=handler.obtainMessage();
        dogMsg.what=DOGCLOSEDOORSHOW;
        dogMsg.arg1=1;
        dogMsg.obj=content;
        handler.sendMessage(dogMsg);
    }

    private void setOpenDoorWarn(String content){
        Message dogMsg=handler.obtainMessage();
        dogMsg.what=DOGOPENDOORSHOW;
        dogMsg.arg1=1;
        dogMsg.obj=content;
        handler.sendMessage(dogMsg);
    }

    private void sendFlowNum(int num){
        Message message=handler.obtainMessage();
        message.what=SHOWFLOW;
        message.arg1=num;
        handler.sendMessage(message);
    }

    @Override
    public void sendAdvert(List<AlarmBean> alarmBeanList) {
        if (!adcacheLinkedDeque.isEmpty()){
            Log.i(TAG, "sendAdvert: 收到广告==如果当前广告列表里面有则清除列表" );
            adcacheLinkedDeque.clear();
        }

        adcacheLinkedDeque.add(alarmBeanList);
        synchronized (advertObject) {
            advertObject.notifyAll();
        }

    }

    @Override
    public void showDogBoxState(double water, double houseTem, boolean doorStateFlag, boolean urgenStateFlag, boolean waterLevelFlag) {

        double tem=FlyUtil.getInvirTemp(DogActivity.this);
        DecimalFormat decimalFormat=new DecimalFormat("#.0");
        this.invirTem=Double.parseDouble(decimalFormat.format(tem));
        Log.i(TAG, "得到的洗狗机状态showDogBoxState: 水温="+water+";室温="+houseTem+";环境温度="+invirTem+";是否关门="+doorStateFlag+";应急按钮是否正常="+urgenStateFlag+";水位是否正常="+waterLevelFlag );
        this.waterTem=water;
        this.houseTem=houseTem;
        this.waterTem1=water;
        this.houseTem1=houseTem;
        this.doorFlag=doorStateFlag;
        this.urgenFlag=urgenStateFlag;
        this.waterLevelFlag=waterLevelFlag;
        DogEventBean dogEventBean=new DogEventBean();
        dogEventBean.setOrder("Z00");
        dogLinkedDeque.add(dogEventBean);
        synchronized (dogObject) {
            dogObject.notifyAll();
        }
    }

    /**
     *
     * @param water 水温
     * @param houseTem 室温
     * @param doorStateFlag 接近开关状态
     * @param urgenStateFlag 紧急按键状态
     * @param waterLevelFlag 水位状态
     * @param bodyWashFlag 沐浴露状态
     * @param conditionerFlag 护毛素状态
     * @param disinfectantFlag 消毒液状态
     * @param waterUse 总用水量
     * @param elecUse 总用电量
     * @param elecPumpCurrent 高压水泵电流
     * @param elecHeatingCurrent 风干加热电流
     * @param elecVortexCurrent 旋涡风机电流
     * @param elecAirCurrent 换气风机电流
     * @param elecLiquidCurrent 液体泵电流
     * @param elecWaterPumpCurrent 水泵阀门电流
     * @param elecBodyWashCurrent 沐浴露阀门电流
     * @param elecConditionerCurrent 护毛素阀门电流
     * @param elecDisinfectantCurrent 消毒液阀门电流
     * @param elecDoorCurrent 门锁电流
     */
    @Override
    public void showDogBoxState(double water, double houseTem, boolean doorStateFlag, boolean urgenStateFlag, boolean waterLevelFlag, boolean bodyWashFlag, boolean conditionerFlag, boolean disinfectantFlag, double waterUse, double elecUse, double elecPumpCurrent, double elecHeatingCurrent, double elecVortexCurrent, double elecAirCurrent, double elecLiquidCurrent, double elecWaterPumpCurrent, double elecBodyWashCurrent, double elecConditionerCurrent, double elecDisinfectantCurrent, double elecDoorCurrent) {

        double tem=FlyUtil.getInvirTemp(DogActivity.this);
        DecimalFormat decimalFormat=new DecimalFormat("#.0");
        this.invirTem=Double.parseDouble(decimalFormat.format(tem));
        Log.i(TAG, "第三版得到的洗狗机状态showDogBoxState: 水温="+water+";室温="+houseTem+";环境温度="+invirTem+";是否关门="+doorStateFlag+";应急按钮是否正常="+urgenStateFlag+";水位是否正常="+waterLevelFlag );
        this.waterTem=water;
        this.houseTem=houseTem;
        this.waterTem1=water;
        this.houseTem1=houseTem;
        this.doorFlag=doorStateFlag;
        this.urgenFlag=urgenStateFlag;
        this.waterLevelFlag=waterLevelFlag;
        DogEventBean dogEventBean=new DogEventBean();
        dogEventBean.setOrder("Z00");
        dogLinkedDeque.add(dogEventBean);
        synchronized (dogObject) {
            dogObject.notifyAll();
        }

        //在这里做电量异常上传标记，告警标记   电流异常

    }

    @Override
    public void showBackMechineOrder(String receiveOrder) {

    }

    boolean onceDoFlag=true;//只使用一次标志位
    @Override
    public void showNetworkState(boolean flag) {
        firstAd();

        if (stage>0 && stage<9){
            //说明是在洗狗流程中，但是处于已经付费的情况。所以还是显示流程图

        }else{
            if (flag){
                // 如果是联网的，则显示开始状态
                if (!onceDoFlag){
                    onceDoFlag=true;
                    setFlowMsg("空闲",0);
                    sendFlowNum(9);//变回开始界面

                    if (waterLevelFlag){
                        if (!"正常".equals(dogStateStr)){
                            dogStateStr="正常";
                            Message message=handler.obtainMessage();
                            message.obj=dogStateStr;
                            message.what=DOGDEVICESTATE;
                            handler.sendMessage(message);
                        }
                    }

                }
            }else{
                // 如果是没有联网的，则显示无网络状态
                if (onceDoFlag){
                    onceDoFlag=false;
                    handler.sendEmptyMessage(NONETWORK);

                    if (!"网络异常".equals(dogStateStr)){
                        dogStateStr="网络异常";
                        Message message=handler.obtainMessage();
                        message.obj=dogStateStr;
                        message.what=DOGDEVICESTATE;
                        handler.sendMessage(message);
                    }

                }
            }

        }
    }

    private void decideActivity(String data){
        Log.i(TAG, "decideActivity 收到功能码: "+data);
//        String functionTxt=FlyTextUtil.readFile(FlyTextUtil.SDPATH,FlyTextUtil.FUNCTION);
        //在functionTxt的内容等于0或者是和之前的data不一样的时候，才会重新
        if (data!=null && (function.length()==0 || !function.equals(data))){
            Log.i(TAG, "decideActivity: " );
            FlyTextUtil.writeTxtFile(data,FlyTextUtil.SDPATH+FlyTextUtil.TXTDIR,FlyTextUtil.FUNCTION);
        }else{
            Log.i(TAG, "decideActivity: data值为--"+data+";functionTxt值--"+function );
        }

    }


    @Override
    protected void onDestroy() {
        isDestroy=false;
        Log.e("tiwolf", "uncaughtException: DogActivity--收集到app遭遇到未知错误，清除缓存，异常线程 出现线程正常结束的情况" );
        try {
            unregisterReceiver(mNetWorkBroadCastReciver);
            handler.removeCallbacksAndMessages(null);
            if (mSocketService!=null){
                mSocketService.onDestroy();
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        try {
            if (gaodeLocationUtils!=null){
                gaodeLocationUtils.cancelLocation();
                gaodeLocationUtils = null;
            }

            LocationUtils.unRegisterListener(DogActivity.this);
        }catch (Exception e){
            e.printStackTrace();
        }

        try {
            unbindService(mServiceConnection);
        }catch (Exception e){
            e.printStackTrace();
        }


        try {
            if (textToSpeech!=null){
                textToSpeech.stop();
                textToSpeech.shutdown();
                textToSpeech = null;
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        try {

            if (mPlayer!=null){
                mPlayer.setDisplay(null);
                if (mPlayer.isPlaying()){
                    mPlayer.stop();
//                    mPlayer.reset();
                }
                if (mPlayer != null) {
                    mPlayer.reset();
                    mPlayer.release();
                    mPlayer = null;
                }

            }
        }catch (Exception e){
            e.printStackTrace();
        }

        try {
            if (upLoadWorker != null) {
                upLoadWorker.interrupt();
                try {
                    upLoadWorker.join();
                } catch (InterruptedException e) {
                    upLoadWorker.interrupt();
                }
                upLoadWorker = null;
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        Log.i(TAG, "onDestroy: 摄像头初始化当前已经销毁进程555");
        try {
            if (ReceiveWorker != null) {
                ReceiveWorker.interrupt();
                try {
                    ReceiveWorker.join();
                } catch (InterruptedException e) {
                    ReceiveWorker.interrupt();
                }
                ReceiveWorker = null;
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        try {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

            if (mTelephonyManager!=null)
                mTelephonyManager.listen(mListener, PhoneStatListener.LISTEN_NONE);
        }catch (Exception e){
            e.printStackTrace();
        }

        try {
            sqliteManager.closeDb();
        }catch (Exception e){
            e.printStackTrace();
        }



        if (policeMap!=null){
            policeMap.clear();
            policeMap=null;
        }

        if (verParams!=null){
            verParams.clear();
            verParams=null;
        }

        if (downParams!=null){
            downParams.clear();
            downParams=null;
        }

        if (errorMap!=null){
            errorMap.clear();
            errorMap=null;
        }

        if (params!=null){
            params.clear();
            params=null;
        }

        if(uploadParams!=null){
            uploadParams.clear();
            uploadParams=null;
        }

        super.onDestroy();
    }
}
